2013-03-28 93 views
1

我已經使用mongodb「2d」索引將我的舊集合轉換爲具有geojson規範「2dsphere」索引的集合。問題在於查詢大約需要11秒才能收集大約2個lac對象。以前是需要大約100毫秒的查詢。我的文檔如下。Mongodb 2.4 2dsphere查詢很慢

{ "_id": ObjectId("4f9c2aa2d142b9882f02a3b3"), "geonameId": NumberInt(1106542), "name": "Chitungwiza", "feature code": "PPL", "country code": "ZW", "state": "Harare Province", "population": NumberInt(340360), "elevation": "", "timezone": "Africa\/Harare", "geolocation": { "type": "Point", "coordinates": { "0": 31.07555, "1": -18.01274 } } }

我解釋查詢的輸出如下。

db.city_info.find({"geolocation":{'$near':{ '$geometry': { 'type':"Point",coordinates:[73,23] } }}}).explain() 

{ 
"cursor" : "S2NearCursor", 
"isMultiKey" : true, 
"n" : 172980, 
"nscannedObjects" : 172980, 
"nscanned" : 1121804, 
"nscannedObjectsAllPlans" : 172980, 
"nscannedAllPlans" : 1121804, 
"scanAndOrder" : false, 
"indexOnly" : false, 
"nYields" : 13, 
"nChunkSkips" : 0, 
"millis" : 13841, 
"indexBounds" : { 

}, 
"nscanned" : 1121804, 
"matchTested" : NumberLong(191431), 
"geoMatchTested" : NumberLong(191431), 
"numShells" : NumberLong(373), 
"keyGeoSkip" : NumberLong(930373), 
"returnSkip" : NumberLong(933610), 
"btreeDups" : NumberLong(0), 
"inAnnulusTested" : NumberLong(191431), 
"server" : "..." 
} 

請讓我知道如何解決問題並縮短查詢時間。

回答

0

我已經解決了這個問題。 $ near命令需要$ maxDistance參數:http://docs.mongodb.org/manual/applications/2dsphere/。只要我提供$ maxDistance,查詢時間就會縮短到小於100毫秒。

+0

$ near不需要$ maxDistance。您執行的查詢已成功並正確地返回了您要求的內容。 – 2013-07-08 17:02:21

2

根據您的建議,$ near命令不需要$ 2dsphere數據庫的$ maxDistance參數。添加$ maxDistance只是指定一個範圍,將查詢結果的數量減少到可管理的數量。如果您的體驗從「2d」變爲「2dsphere」樣式索引的原因有所不同,那麼如果沒有指定「2d」索引,則默認限制爲100。如您所見,2dsphere索引的默認查詢計劃不會強制實施此限制,因此查詢正在掃描整個索引(「nscannedObjects」:172980)。如果您在「2d」索引上運行相同的查詢,您會看到「n」和「nscannedObjects」僅爲100,這說明了成本差異。

如果所有的項目都在$ maxDistance範圍內(以$ maxDistance 20M米,例如嘗試),你會看到查詢性能下降回到它是離不開它。在任何一種情況下,使用limit()來告訴查詢計劃只掃描索引內的必要結果以防止失控,尤其是對於較大的數據集時非常重要。

+2

這是一個可以接受的答案,對吧?你有可能爲我做這件事嗎? – 2013-07-19 03:10:54

+0

關注爲什麼你低估了這個答案?這是正確的。 – 2014-06-10 15:11:35

+0

我意識到這是非常舊的,但只是添加,我運行一個2dsphere索引$ 2近似查詢和2d索引,數據是完全一樣的。兩者都限制爲100,但二維索引查詢返回0.2秒,2dsphere索引查詢需要10s + ..所以我不認爲使用限制是正確的答案 – 2015-03-06 15:15:34