前几天看到一个关于 MongoDB 深入索引的PPT
然后给x 和 y进行联合索引 db.good.ensureIndex({x:1,y:1})
我们来进行这样的查找
> db.good.find({x:{$gte:4}, y:'c'}).explain()
{
"cursor" : "BtreeCursor x_1_y_1",
"nscanned" : 7,
"nscannedObjects" : 2,
"n" : 2,
"millis" : 0,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
"x" : [
[
4,
1.7976931348623157e+308
]
],
"y" : [
[
"c",
"c"
]
]
}
}
可以看出 nscanned 非常高! 而 n只有 2 .官网上有这样一句话:
Ifnscannedis much higher thannreturned, the database is scanning many objects to find the target objects. Consider creating an index to improve this.
这里nscanned可以认为是扫描的记录数.n为返回的记录数
让我们配合PPT看下 nscanned:7是怎么来的:
这是MongoDB的B-tree索引树,因为x>=4 && y='c',所以先选择左枝搜索,左枝搜索了4/g 和 5/c ,(5/c符合条件),然后搜索 右枝 搜索了 7/e, 6/a ,8/c, 9/f ,(8/c符合条件). 任何 符合的 x都要被check一下.
延伸:
看了PPT后到此结尾了, 真遇到这种情况,效率可不乐观,于是稍微思考了下, y 在 这颗树中只有两个节点含有,也就是说 既然是 '与' 那就只要先把 y 筛选出来 ,搜索次数就大大减半了 .
我们在 y 上再进行Basic Indexes 的建立.
db.good.ensureIndex({y:1})这样如果搜索时会先 搜索 y ,也就只有2次搜索了.看下实际情况: > db.good.find({x:{$gte:4}, y:'c'}).explain() { "cursor" : "BtreeCursor y_1", "nscanned" : 2, "nscannedObjects" : 2, "n" : 2, "millis" : 0, "nYields" : 0, "nChunkSkips" : 0, "isMultiKey" : false, "indexOnly" : false, "indexBounds" : { "y" : [ [ "c", "c" ] ] } }正如预料的一样. 直接走 基本索引了.