【问题标题】:Optimizing GeoJSON MongoDB queries优化 GeoJSON MongoDB 查询
【发布时间】:2015-02-02 22:15:07
【问题描述】:

我有一些多边形存储在我的 mongoDB 中的 GeoJSON 中。

客户端发送要加载的框列表(框是常规网格的单元格)。

检索它们的正常方法是对每个框进行 GeoJSON 查询,但是当我有很多框时会很慢。

我不想检索重复项(位于两个单元格上的多边形会返回两次),所以我制作了一个检索到的多边形列表pks,以便在接下来的查询中忽略它们。

给定:

box = [ [ [ 0, 0 ], [ 1, 0 ], [ 1, 1 ], [ 0, 1 ], [ 0, 0 ] ] ]  // the box to load
pks = [ ObjectId("54cf535cfe022e01ab4932f5"), ObjectId("54cf535cfe022e01ab4932f6") ] // the list of polygons already retrieved

使用 mongoDB 我会得到这样的东西:

for box in boxes:
    db.places.find( { points: 
        { $geoIntersects: { $geometry: { type: "Polygon" ,  coordinates: box } } },
        { _id: { $nin: pks } } 
    } )

我使用的是 MongoEngine,所以我有以下内容:

pks = []
for box in boxes:
   p = Polygon.objects(points__geo_intersects=box, pk__nin=pks)
   if len(p)>0:       
      pks += p.scalar("id")

我有三个问题:

1.有没有更有效的方法来使用这种方法查询多边形?

2。使用包含位于单元格上的多边形引用列表的 Cell 对象会更快吗?

在 MongoEngine 中,我将拥有以下模型:

class Cell(Document):
    x = DecimalField()
    y = DecimalField()
    polygons = ListField(ReferenceField('Polygon'))

    meta = {
        'indexes': [[ ("x", 1), ("y", 1) ]]
    }

要加载的框列表将是与要加载的单元格对应的坐标。

这将给 MongoEngine:

polygons = {}

for b in boxes:
    cell = Cell.objects.get(x=b['x'], y=b['y'])

    for polygon in cell.polygons:
        if not polygons.has_key(polygon.pk):
            polygons[polygon.pk] = polygon.to_json()

3.有没有更有效的方法来用这种方法查询多边形?(我想我应该使用select_related(),也许可以直接在mongoDB查询中过滤多边形以避免检索重复)

【问题讨论】:

  • 我刚刚做了一个基准测试:第一种方法检索多边形需要 2.03 秒,第二种方法需要 0.65 秒。
  • 嗯...实际上我刚刚发现差异可能来自pk__nin=pks,这需要更长的时间。现在我用第一种方法得到了更快的结果......我会在午餐后进一步调查......

标签: mongodb geojson mongoengine


【解决方案1】:

在做了一些基准测试之后,我可以回答我自己的问题:使用诸如Cell 之类的中间对象并没有明显更快。

但是,在查询中使用主键列表,如下所示:

pks = []
for box in boxes:
   p = Polygon.objects(points__geo_intersects=box, pk__nin=pks)
   if len(p)>0:       
      pks += p.scalar("id")

比使用字典忽略重复项要慢得多,如下所示:

polygons = {}
for box in boxes:
   p = Polygon.objects(points__geo_intersects=box)
   for polygon in p:
      if not polygons.has_key(polygon.pk):
          polygons[polygon.pk] = polygon.to_json()

【讨论】:

    猜你喜欢
    • 2015-01-21
    • 2015-01-09
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 2021-09-03
    • 2019-10-25
    • 2020-07-05
    相关资源
    最近更新 更多