1. 程式人生 > 實用技巧 >【趙強老師】MongoDB中的索引(下)

【趙強老師】MongoDB中的索引(下)

(四)索引的型別三:複合索引(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()

(七)小結

  • 複合索引是基於多個鍵(列)上建立的索引
  • 複合索引在建立的時候可以為其每個鍵(列)來指定排序方法
  • 索引鍵列的排序方法影響查詢在排序時候的操作,方向一致或相反的才能被匹配
  • 複合索引與字首索引通常在匹配的情形下才能被使用