首页 > 解决方案 > Geodjango - 内存中的 r-tree 索引

问题描述

如何使用 Geodjango 在内存中创建 r-tree 索引?

我有许多固定的多边形(硬编码),我想检查一个点属于这些多边形中的哪个。

我想在内存中执行此操作以避免依赖空间数据库。

标签: pythondjangogeodjangor-tree

解决方案


您可以使用一个名为:的库Rtree,它独立于启用空间的数据库。

教程:

# Import the library and create an index:
from rtree import index
idx = index.Index()

# Insert your fixed polygons to the index by the envelope (bounding box)
# coordinates of those polygons:
for index, polygon in enumerate(my_polygon_list):
    idx.insert(index, polygon.envelope)

# To query with a point you can do the following (explanation after the example):
potential_polys = list(idx.intersection((point.x, point.y, point.x, point.y)))

分开来:

  • 教程中关于如何设置 Rtree 索引的部分非常简单。
  • 几何的边界框(或包络)坐标必须具有以下格式:
    (xmin, ymin, xmax, ymax)(left, bottom, right, top)
  • 在文档中指出:

    插入一个点,即 where left == right&& top == bottom,本质上将在索引中插入一个点条目,而不是复制额外的坐标并插入它们。但是,没有明确插入单个点的捷径。

    所以我们使用这个“怪癖”将我们的点应用于intersection索引上的多边形查询。


推荐阅读