关于nosql:赵强老师MongoDB中的索引下

2次阅读

共计 1501 个字符,预计需要花费 4 分钟才能阅读完成。

(四)索引的类型三:复合索引(Compound Index)**

MongoDB 反对复合索引,行将多个键组合到一起创立索引。该形式称为复合索引,或者也叫组合索引,该形式可能满足多键值匹配查问应用索引的情景。其次复合索引在应用的时候,也能够通过前缀法来应用索引。MongoDB 中的复合索引与关系型数据库基本上统一。在关系型数据库中复合索引应用的一些准则同样实用于 MongoDB。

在后面的内容中,咱们曾经在 emp 汇合上创立了一个复合索引,如下:

db.emp.createIndex({"deptno":1,"sal":-1})

上面应用不同的过滤条件查问文档,查看相应的执行打算:

(1)仅应用 deptno 作为过滤条件

db.emp.find({"deptno":10}).explain()

(2)应用 deptno、sal 作为过滤条件

db.emp.find({"deptno":10,"sal":3000}).explain()

(3)应用 deptno、sal 作为过滤条件,但把 sal 放在后面

db.emp.find({"sal":3000,"deptno":10}).explain()

(4)仅应用 sal 作为过滤条件

db.emp.find({"sal":3000}).explain()

(五)复合索引与排序

复合索引创立时按升序或降序来指定其排列形式。对于单键索引,其程序并不是特地重要,因为 MongoDB 能够在任一方向遍历索引。对于复合索引,按何种形式排序可能决定该索引在查问中是否被应用到。

db.emp.createIndex({"deptno":1,"sal":-1})

在后面的内容中,咱们曾经在 deptno 上依照升序、sal 上依照降序建设了复合索引,上面测试不同的排序的下,是否执行了索引:

应用了索引的状况:db.emp.find().sort({"deptno":1,"sal":-1}).explain()
db.emp.find().sort({"deptno":-1,"sal":1}).explain()

没有应用索引的状况:db.emp.find().sort({"deptno":1,"sal":1}).explain()
db.emp.find().sort({"deptno":-1,"sal":-1}).explain()

替换两个列的地位,再进行测试。

(六)复合索引与索引前缀

索引前缀指的是复合索引的子集,如果存在如下索引:

db.emp.createIndex({"deptno":1,"sal":-1,"job":1})

那么就存在以下的索引前缀:{"deptno":1}
{"deptno":1,"sal":-1}

在 MongoDB 中,下列查问过滤条件情景中,索引将会被应用到:

db.emp.find().sort({deptno:1,sal:-1,job:1}).explain()
db.emp.find().sort({deptno:1,sal:-1}).explain()
db.emp.find().sort({deptno:1}).explain()

下列查问过滤条件情景中,索引将不会被应用到:

db.emp.find().sort({deptno:1,job:1}).explain()
db.emp.find().sort({sal:-1,job:1}).explain()

(七)小结

  • 复合索引是基于多个键 (列) 上创立的索引
  • 复合索引在创立的时候能够为其每个键 (列) 来指定排序办法
  • 索引键列的排序办法影响查问在排序时候的操作,方向统一或相同的能力被匹配
  • 复合索引与前缀索引通常在匹配的情景下能力被应用

正文完
 0