0

I have a question regarding compound indexes that i cant seem to find, or maybe just have misunderstood.

Lets say i have created a compound index {a:1, b:1, c:1}. This should make according to http://docs.mongodb.org/manual/core/indexes/#compound-indexes

the following queries fast.

db.test.find({a:"a", b:"b",c:"c"})
db.test.find({a:"a", b:"b"})
db.test.find({a:"a"})

As i understand it the order of the query is very important, but is it only that explicit subset of {a:"a", b:"b",c:"c"} order that is important?

Lets say i do a query

db.test.find({d:"d",e:"e",a:"a", b:"b",c:"c"})

or

db.test.find({a:"a", b:"b",c:"c",d:"d",e:"e"})

Will these render useless for that specific compound index?

4

1 回答 1

1

MongoDB 中的复合索引采用前缀机制a{a,b}按顺序将被视为复合索引的前缀,但是,查询本身中字段的顺序通常无关紧要。

所以让我们举个例子:

db.test.find({d:"d",e:"e",a:"a", b:"b",c:"c"})

实际上会使用一个索引:

db.ghghg.find({d:1,e:1,a:1,c:1,b:1}).explain()
{
        "cursor" : "BtreeCursor a_1_b_1_c_1",
        "isMultiKey" : false,
        "n" : 1,
        "nscannedObjects" : 1,
        "nscanned" : 1,
        "nscannedObjectsAllPlans" : 2,
        "nscannedAllPlans" : 2,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 0,
        "indexBounds" : {
                "a" : [
                        [
                                1,
                                1
                        ]
                ],
                "b" : [
                        [
                                1,
                                1
                        ]
                ],
                "c" : [
                        [
                                1,
                                1
                        ]
                ]
        },
        "server" : "ubuntu:27017"
}

自从a并且b在那里。

db.test.find({a:"a", b:"b",c:"c",d:"d",e:"e"})

取决于 和 的选择性和d基数e。它将使用复合索引,但至于它是否会以允许良好查询性能的方式有效地使用它,很大程度上取决于其中的内容。

于 2013-04-25T10:32:49.330 回答