2013-10-14 47 views
4

我試圖檢索一堆存儲在我的數據庫中的多邊形,並按半徑排序。所以我用簡單的$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索引時)

+0

我有類似的行爲,你有沒有更好地瞭解發生了什麼? –

回答

-2

首先, ,s2Cursor表示查詢使用地理索引。 排序操作速度慢可能有多種原因,排序操作需要內存,也許服務器的內存很少,您應該考慮在代碼中執行排序操作,而不是在服務器端執行。

+1

問題是,爲什麼它不使用複合索引 – kilianc