【赵强老师】MongoDB中的索引(下)

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

MongoDB支持复合索引,即将多个键组合到一块儿建立索引。该方式称为复合索引,或者也叫组合索引,该方式可以知足多键值匹配查询使用索引的情形。其次复合索引在使用的时候,也能够经过前缀法来使用索引。MongoDB中的复合索引与关系型数据库基本上一致。在关系型数据库中复合索引使用的一些原则一样适用于MongoDB。数据库

在前面的内容中,咱们已经在emp集合上建立了一个复合索引,以下:测试

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

下面使用不一样的过滤条件查询文档,查看相应的执行计划:code

(1)仅使用deptno做为过滤条件blog

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()

交换两个列的位置,再进行测试。

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

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

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()

(七)小结

  • 复合索引是基于多个键(列)上建立的索引
  • 复合索引在建立的时候能够为其每一个键(列)来指定排序方法
  • 索引键列的排序方法影响查询在排序时候的操做,方向一致或相反的才能被匹配
  • 复合索引与前缀索引一般在匹配的情形下才能被使用

相关文章
相关标签/搜索