【问题标题】:Sort on $geoWithin geospatial query in MongoDB在 MongoDB 中对 $geoWithin 地理空间查询进行排序
【发布时间】:2013-10-22 13:47:23
【问题描述】:

我正在尝试检索存储在我的数据库中的一堆多边形,并按半径对它们进行排序。所以我用一个简单的$geoWithin写了一个查询。

所以,没有排序的代码看起来像这样:

db.areas.find(
   {
       "geometry" : {
          "$geoWithin" : {
              "$geometry" : {
                    "type" : "Polygon",
                    "coordinates" : [ [ /** omissis: array of points **/ ] ] 
                }
            }
        }
    }).limit(10).explain();

解释结果如下:

{
    "cursor" : "S2Cursor",
    "isMultiKey" : true,
    "n" : 10,
    "nscannedObjects" : 10,
    "nscanned" : 367,
    "nscannedObjectsAllPlans" : 10,
    "nscannedAllPlans" : 367,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 2,
    "indexBounds" : {

    },
    "nscanned" : 367,
    "matchTested" : NumberLong(10),
    "geoTested" : NumberLong(10),
    "cellsInCover" : NumberLong(27),
    "server" : "*omissis*"
}

(虽然很快,但显示为光标S2Cursor,让我明白我的复合索引没有被使用。但是,它很快)

因此,每当我尝试添加sort 命令时,只需使用.sort({ radius: -1 }),查询就会变得非常缓慢:

{
    "cursor" : "S2Cursor",
    "isMultiKey" : true,
    "n" : 10,
    "nscannedObjects" : 58429,
    "nscanned" : 705337,
    "nscannedObjectsAllPlans" : 58429,
    "nscannedAllPlans" : 705337,
    "scanAndOrder" : true,
    "indexOnly" : false,
    "nYields" : 3,
    "nChunkSkips" : 0,
    "millis" : 3186,
    "indexBounds" : {

    },
    "nscanned" : 705337,
    "matchTested" : NumberLong(58432),
    "geoTested" : NumberLong(58432),
    "cellsInCover" : NumberLong(27),
    "server" : "*omissis*"
}

使用 MongoDB 扫描所有文档。显然,我尝试添加复合索引,例如 { radius: -1, geometry : '2dsphere' }{ geometry : '2dsphere' , radius: -1 },但没有任何帮助。还是很慢。

我会知道我是否以错误的方式使用复合索引,如果S2Cursor 告诉我应该改变我的索引策略,总的来说,我做错了什么。

(PS:我使用的是 MongoDB 2.4.5+,所以问题不是由使用 2dsphere 索引时复合索引中的第二个字段升序引起的,如此处报告https://jira.mongodb.org/browse/SERVER-9647

【问题讨论】:

  • 我有类似的行为,你有没有更好地理解发生了什么?

标签: mongodb sorting geospatial


【解决方案1】:

首先,s2Cursor 表示查询使用地理索引。 排序操作慢可能有多种原因,排序操作需要内存,可能你的服务器内存很少,你应该考虑在代码中执行排序操作,而不是在服务器端。

【讨论】:

  • 问题是,为什么不使用复合索引
猜你喜欢
  • 2023-03-29
  • 1970-01-01
  • 2015-06-07
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
  • 1970-01-01
  • 2014-05-03
  • 2019-09-23
相关资源
最近更新 更多