
(四)索引的型別三:復合索引(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()
(七)小結
- 復合索引是基于多個鍵(列)上創建的索引
- 復合索引在創建的時候可以為其每個鍵(列)來指定排序方法
- 索引鍵列的排序方法影響查詢在排序時候的操作,方向一致或相反的才能被匹配
- 復合索引與前綴索引通常在匹配的情形下才能被使用

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/237524.html
標籤:NoSQL
上一篇:MySQL常用命令(DDL)
