2012-11-03 32 views
5
I have a collection such as: 
{u'_id': ObjectId('5094cc44e3f0f827b3618918'), 
    u'xxx': 0}, 
{u'_id': ObjectId('5094cc44e3f0f827b3618919'), 
    u'xxx': 1}, 
{u'_id': ObjectId('5094cc44e3f0f827b361891a'), 
    u'xxx': 2}, 
{u'_id': ObjectId('5094cc44e3f0f827b361891b'), 
    u'xxx': 3}, 
{u'_id': ObjectId('5094cc44e3f0f827b361891c'), 
    u'xxx': 4} 
... 

當我創建索引,例如:Mongodb索引是如何工作的?

db.test.ensure_index([("_id",-1),("xxx",1)]) 
db.test.ensure_index([("xxx",1)]) 

然後,我用的解釋,如:

db.test.find({"xxx":1}).sort("_id",-1).skip(5).limit(5).explain() 

result is: 
{u'allPlans': [{u'cursor': u'BtreeCursor _id_ reverse', 
       u'indexBounds': {u'_id': [[{u'$maxElement': 1}, 
              {u'$minElement': 1}]]}, 
       u'n': 9, 
       u'nscanned': 34, 
       u'nscannedObjects': 34}, 
       {u'cursor': u'BtreeCursor xxx_1', 
       u'indexBounds': {u'xxx': [[1, 1]]}, 
       u'n': 34, 
       u'nscanned': 34, 
       u'nscannedObjects': 34}, 
       {u'cursor': u'BtreeCursor _id_-1_xxx_1', 
       u'indexBounds': {u'_id': [[{u'$maxElement': 1}, 
              {u'$minElement': 1}]], 
           u'xxx': [[1, 1]]}, 
       u'n': 10, 
       u'nscanned': 38, 
       u'nscannedObjects': 10}, 
       {u'cursor': u'BasicCursor', 
       u'indexBounds': {}, 
       u'n': 16, 
       u'nscanned': 34, 
       u'nscannedObjects': 34}], 
u'cursor': u'BtreeCursor xxx_1', 
u'indexBounds': {u'xxx': [[1, 1]]}, 
u'indexOnly': False, 
u'isMultiKey': False, 
u'millis': 1, 
u'n': 5, 
u'nChunkSkips': 0, 
u'nYields': 0, 
u'nscanned': 34, 
u'nscannedAllPlans': 140, 
u'nscannedObjects': 34, 
u'nscannedObjectsAllPlans': 112, 
u'scanAndOrder': True, 
u'server': u'ubuntu:27017'} 

從N,nscanned和nscnnedObjects的次數,我認爲它應該使用u'BtreeCursor id -1_xxx_1'as cursor,but Why It u'cursor':u'BtreeCursor xxx_1',? 任何人都可以給我一些建議嗎?我對索引優化有一點了解。

+0

如果你在JavaScript(官方的mongo shell語言)中提供了示例,這將有所幫助。 –

+0

這是一個Python語言。我只想知道,當我使用find('xxx')。sort('_ id', - 1)時,我如何創建一個索引? – halostack

+0

把你想排序的字段放在索引定義的末尾:'db.test.ensureIndex({xxx:1,_id:-1})' –

回答

3

索引中字段的順序很重要;爲您找到最好的複合索引和排序例子其實是:

db.test.ensure_index([("xxx",1),("_id",-1)]) 

因爲你的搜索條件是場「XXX」,首先把這個領域的指數會發現比_id搜索,然後過濾更多結果到符合您的xxx標準的文件。

如果您查看allPlans中查詢優化程序考慮的每個計劃的n號碼,實際上BtreeCursor xxx_1索引會返回大多數結果(34)。其他指標會返回9,10和16個結果..所以對於給定的搜索條件效率較低。

有關索引優化的更多信息,本文對您有幫助:Optimizing MongoDB Compound Indexes