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}
...
Run Code Online (Sandbox Code Playgroud)
当我创建索引如:
db.test.ensure_index([("_id",-1),("xxx",1)])
db.test.ensure_index([("xxx",1)])
Run Code Online (Sandbox Code Playgroud)
那么,我用的解释如下:
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'}
Run Code Online (Sandbox Code Playgroud)
来自n,nscanned和nscnnedObjects的num,我认为它应该使用u'BtreeCursor id -1_xxx_1'作为光标,但为什么它使用u'cursor':u'BtreeCursor xxx_1',?任何人都可以给我一些建议吗?我对索引优化有一点了解.
索引中字段的顺序很重要;您的查找和排序示例的最佳复合索引实际上是:
db.test.ensure_index([("xxx",1),("_id",-1)])
Run Code Online (Sandbox Code Playgroud)
由于您的搜索条件位于字段“xxx”上,因此将该字段放在索引中的第一个字段会比搜索_id然后过滤到与您的xxx条件匹配的文档找到更多的结果。
如果查看n中查询优化器考虑的每个计划的数量allPlans,BtreeCursor xxx_1索引实际上返回最多的结果 (34)。其他索引返回 9、10 和 16 个结果......因此对于给定的搜索条件效率较低。
有关索引优化的更多信息,这篇文章非常有帮助:优化 MongoDB 复合索引。
| 归档时间: |
|
| 查看次数: |
4512 次 |
| 最近记录: |