【发布时间】: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