我试图检索一堆存储在我的数据库中的多边形,并按半径排序。所以我用简单的$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
,让我明白我的化合物指数没有被使用过,但它的速度很快)
所以,无论何时我RY添加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+,所以问题不是由复合索引第二个字段上升所致使用,问题报告https://jira.mongodb.org/browse/SERVER-9647 2dsphere索引时)
我有类似的行为,你有没有更好地了解发生了什么? –