【趙強老師】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()

(七)小結

  • 複合索引是基於多個鍵(列)上建立的索引
  • 複合索引在建立的時候能夠爲其每一個鍵(列)來指定排序方法
  • 索引鍵列的排序方法影響查詢在排序時候的操做,方向一致或相反的才能被匹配
  • 複合索引與前綴索引一般在匹配的情形下才能被使用

相關文章
相關標籤/搜索