未选择Mongo复合指数

时间:2015-02-22 16:41:37

标签: mongodb indexing

我有以下架构:

{
    score  : { type : Number},
    edges : [{name : { type : String }, rank  : { type : Number }}],
    disable : {type : Boolean},
}

我尝试为以下查询构建索引

db.test.find( {
    disable: false, 
    edges: { $all: [ 
        { $elemMatch: 
            { name: "GOOD" } ,
        }, 
        { $elemMatch: 
            { name: "GREAT" } ,
        }, 
    ] }, 
}).sort({"score" : 1})
.limit(40)
.explain()

首先尝试

当我创建索引名称"得分" :

{
    "edges.name" : 1,
    "score" : 1
}

'解释'退回:

{ 
  "cursor" : "BtreeCursor score",
  ....
}

第二次尝试

当我改变"得分"到:

{
    "disable" :  1,
    "edges.name" : 1,
    "score" : 1
}

'解释'退回:

 "clauses" : [ 
    {
        "cursor" : "BtreeCursor name",
        "isMultiKey" : true,
        "n" : 0,
        "nscannedObjects" : 304,
        "nscanned" : 304,
        "scanAndOrder" : true,
        "indexOnly" : false,
        "nChunkSkips" : 0,
        "indexBounds" : {
            "edges.name" : [ 
                [ 
                    "GOOD", 
                    "GOOD"
                ]
            ]
        }
    }, 
    {
        "cursor" : "BtreeCursor name",
        "isMultiKey" : true,
        "n" : 0,
        "nscannedObjects" : 304,
        "nscanned" : 304,
        "scanAndOrder" : true,
        "indexOnly" : false,
        "nChunkSkips" : 0,
        "indexBounds" : {
            "edges.name" : [ 
                [ 
                    "GOOD", 
                    "GOOD"
                ]
            ]
        }
    }
],
"cursor" : "QueryOptimizerCursor",
....
}

'姓名' index是:

{
    'edges.name' : 1
 }

为什么mongo拒绝使用'禁用'索引中的字段? (我已尝试过其他字段,除了'禁用'但遇到同样的问题)

1 个答案:

答案 0 :(得分:1)

看起来查询优化器正在选择效率最高的索引,而edges.name上的索引效果最好。我根据您的架构插入了几个文档来重新创建您的集合。然后我在下面创建了复合索引。

db.test.ensureIndex({
    "disable" :  1,
    "edges.name" : 1,
    "score" : 1
});

在对您指定的查询运行说明时,使用了索引。

> db.test.find({ ... }).sort({ ... }).explain()
{
    "cursor" : "BtreeCursor disable_1_edges.name_1_score_1",
    "isMultiKey" : true,
    ...
}

但是,只要我在edges.name上添加了索引,查询优化器就会为查询选择该索引。

> db.test.find({ ... }).sort({ ... }).explain()
{
"cursor" : "BtreeCursor edges.name_1",
"isMultiKey" : true,
...
}

如果您希望查询使用复合索引,您仍然可以提示另一个索引。

> db.test.find({ ... }).sort({ ... }).hint("disable_1_edges.name_1_score_1").explain()
{
    "cursor" : "BtreeCursor disable_1_edges.name_1_score_1",
    "isMultiKey" : true,
    ...
}

[编辑:添加了与使用$all相关的可能解释。]

请注意,如果您在没有$all的情况下运行查询,则查询优化器会使用复合索引。

> db.test.find({
        "disable": false,
        "edges": { "$elemMatch": { "name": "GOOD" }}})
    .sort({"score" : 1}).explain();
{
    "cursor" : "BtreeCursor disable_1_edges.name_1_score_1",
    "isMultiKey" : true,
    ...
}

我认为这里的问题是您正在使用$all。正如您在explain字段的结果中看到的那样,有一些子句,每个子句都与您使用$all搜索的值之一相关。因此,查询必须为每个子句查找disableedges.name的所有对。我的直觉是,使用复合索引进行的这两次运行比直接查看edges.name然后清除disable的查询慢。这可能与this问题和this问题有关,您可能需要查看这些问题。

相关问题