分散式文檔存儲資料庫之MongoDB索引管理

  前文我們聊到了MongoDB的簡介、安裝和對collection的CRUD操作,回顧請參考//www.cnblogs.com/qiuhom-1874/p/13941797.html;今天我們來聊下mongodb的索引;

  1、為什麼要有索引?索引的作用是幹嘛的?

  我們知道mongodb通常應用在一些web站點,數據量非常大的場景中;在大數據的場景中,對於我們要查詢一個數據,mongodb是否能夠快速的響應結果就變得尤為的重要;這也是索引存在的意義;索引就是用來幫助我們在很大的數據集中快速查詢我們想要的數據;通常我們在mongodb中插入一條數據時,mongodb會自動給我們添加一個_id的欄位,這個欄位是mongodb內部自己維護,通常情況我們都不會去管它;在關係型資料庫中,我們可以在單個欄位上構建索引,也可以在多個欄位上構建索引,之所以要在多個欄位構建索引是因為我們的查詢條件很可能用到的欄位不只一個;所以我們構建索引的原則是根據查詢條件來構建;比如我們要查詢年齡大於30的用戶有哪些,我們就可以把索引構建在年齡這個欄位上,構建在其他欄位上,對於我們要查詢年齡大於30這個條件來講是沒有意義的;所以構建索引通常我們會去了解用戶最常的查詢,在用戶最常查詢的欄位上構建索引,這樣可以有效提高用戶的查詢;對於mongodb也是一樣的,索引的存在就是為了提高我們的查詢;

  2、為什麼索引能夠幫助我們快速查找呢?

  首先索引是按照我們指定的欄位來構建,構建索引就是把我們指定的欄位抽取出來,然後提前排好序(或者按照一定規律的方式排列好),然後保存為另外一個collection;用戶在查找數據時,mongodb首先會去找索引,看看用戶的條件是否和索引匹配,能夠匹配,索引就能告訴用戶要查詢的數據在那個地方,這樣就很快的找到用戶查詢的數據;假如我們構建的索引沒有匹配用戶的查詢,那麼用戶的查詢會以遍歷的方式去查找,這樣一來無形之中速度就變慢了(原本不加索引,直接遍歷,現在有索引,要先查索引,沒有命中,還要遍歷);所以構建索引,如果一定是數據量很大的情況才構建,數據量小,構建索引不但不會幫助我們快速的查找內容,反而會拖慢我們的查詢速度;其次在很大的數據量上,如果索引構建的欄位沒有被查詢命中,那麼我構建的索引就無意義;

  3、索引在一定程度上是要影響用戶寫的性能

  我們在某個欄位構建好索引以後,用戶在寫數據時,通常會額外多一次寫io;對於寫請求,在沒有索引的情況,用戶只需要寫一次io,有了索引用戶每寫一條數據,都會對應有一次寫索引的io;這樣一來在一定程度上對用戶的寫性能會有影響;但通常我們構建索引都是在讀多寫少的場景中使用;在寫請求不是特別多的場景其實多一次寫io,比起讀請求的壓力我們是可以接受的;更何況有些資料庫支援延遲寫索引,所謂延遲寫索引是指用戶在插入數據時,它不立即寫索引,而是等一段時間再寫,這樣一來就有效的降低寫索引對用戶的寫請求性能的影響;

  上圖主要描述了索引和文檔的關係,在索引里的數據通常是我們指定的欄位,用特定的排列方式組織在一起,在用戶查詢某個數據時,就能夠很快的從索引中拿到對應文檔的位置,從而不用每個文檔挨著遍歷;這也是索引能夠幫助我們快速查找的原因吧;

  4、索引類型

  索引是有類型的,不同類型的索引在內部組織索引的方式各不相同,不同類型的索引給我們查詢帶來的效果也不同;常見的索引類型有b+ tree(平衡樹索引),hash索引、空間索引、全文索引等等;在mongodb中索引也有很多類型,不同的是我們上面說的索引類型,b+ tree,hash索引這些都是從索引內部組織結構來描述;在mongodb中的索引我們是從索引構建的位置來描述;mongodb中的索引有單鍵索引、組合索引、多鍵索引、空間索引、文本索引和hash索引;所謂單鍵索引是指構建在一個欄位上的索引;組合索引指構建在多個欄位上的索引;多鍵索引指將索引構建在一個鍵的值是一個子文檔的欄位上;我們知道文檔和文檔是可以嵌套的,這也意味著一個文檔內部可以引用另一個文檔,一個文檔中的某個鍵對應的值也可以是另外一個子文檔;我們把這種索引構建在一個文檔中的某個鍵是一個子文檔的某個欄位上的索引叫做多鍵索引,它和單鍵索引不是對應的;空間索引指基於位置查詢的索引,但通常這種索引只有用到特定的方法來查詢時,它才會生效,比如使用基於空間位置的函數;文本索引指支援搜索整個文檔中的文本資訊,通常這種索引我們也叫全文索引;hash索引指把某個欄位的值做hash計算後組織的索引;這種索引有個特點就是時間複雜度是o(1);不管數據有多少,在查找數據時所用到的時間都是一樣的;之所以時間複雜度是o(1),原因是hash計算每一個值都是唯一的;這種索引的查找方式有點類似鍵值查找,不同的是hash背後對應的是一個hash桶,先找到hash桶,然後查找到對應的hash值;hash索引和b+樹索引最大的區別是,b+樹索引可以查詢一個範圍,因為樹狀索引通常是把數據組織成一個有序的結構,而hash索引不能,hash索引只能查找一個精確的值,不能查找一個範圍;因為hash索引背後對應的是一個hash值,每個hash值可能都不在一個hash桶,所以我們假如要查詢年齡大於30歲的用戶,用hash索引就不適合,因為30和31的hash值可能就不在一個hash桶上;

  5、在mongodb資料庫上創建索引

  準備數據

> use testdb
switched to db testdb
> for (i=1;i<=1000000;i++) db.peoples.insert({name:"people"+i,age:(i%120),classes:(i%20)})
WriteResult({ "nInserted" : 1 })
> db.peoples.find().count()
1000000
> db.peoples.find()
{ "_id" : ObjectId("5fa943987a7deafb9e543326"), "name" : "people1", "age" : 1, "classes" : 1 }
{ "_id" : ObjectId("5fa943987a7deafb9e543327"), "name" : "people2", "age" : 2, "classes" : 2 }
{ "_id" : ObjectId("5fa943987a7deafb9e543328"), "name" : "people3", "age" : 3, "classes" : 3 }
{ "_id" : ObjectId("5fa943987a7deafb9e543329"), "name" : "people4", "age" : 4, "classes" : 4 }
{ "_id" : ObjectId("5fa943987a7deafb9e54332a"), "name" : "people5", "age" : 5, "classes" : 5 }
{ "_id" : ObjectId("5fa943987a7deafb9e54332b"), "name" : "people6", "age" : 6, "classes" : 6 }
{ "_id" : ObjectId("5fa943987a7deafb9e54332c"), "name" : "people7", "age" : 7, "classes" : 7 }
{ "_id" : ObjectId("5fa943987a7deafb9e54332d"), "name" : "people8", "age" : 8, "classes" : 8 }
{ "_id" : ObjectId("5fa943987a7deafb9e54332e"), "name" : "people9", "age" : 9, "classes" : 9 }
{ "_id" : ObjectId("5fa943987a7deafb9e54332f"), "name" : "people10", "age" : 10, "classes" : 10 }
{ "_id" : ObjectId("5fa943987a7deafb9e543330"), "name" : "people11", "age" : 11, "classes" : 11 }
{ "_id" : ObjectId("5fa943987a7deafb9e543331"), "name" : "people12", "age" : 12, "classes" : 12 }
{ "_id" : ObjectId("5fa943987a7deafb9e543332"), "name" : "people13", "age" : 13, "classes" : 13 }
{ "_id" : ObjectId("5fa943987a7deafb9e543333"), "name" : "people14", "age" : 14, "classes" : 14 }
{ "_id" : ObjectId("5fa943987a7deafb9e543334"), "name" : "people15", "age" : 15, "classes" : 15 }
{ "_id" : ObjectId("5fa943987a7deafb9e543335"), "name" : "people16", "age" : 16, "classes" : 16 }
{ "_id" : ObjectId("5fa943987a7deafb9e543336"), "name" : "people17", "age" : 17, "classes" : 17 }
{ "_id" : ObjectId("5fa943987a7deafb9e543337"), "name" : "people18", "age" : 18, "classes" : 18 }
{ "_id" : ObjectId("5fa943987a7deafb9e543338"), "name" : "people19", "age" : 19, "classes" : 19 }
{ "_id" : ObjectId("5fa943987a7deafb9e543339"), "name" : "people20", "age" : 20, "classes" : 0 }
Type "it" for more
> it
{ "_id" : ObjectId("5fa943987a7deafb9e54333a"), "name" : "people21", "age" : 21, "classes" : 1 }
{ "_id" : ObjectId("5fa943987a7deafb9e54333b"), "name" : "people22", "age" : 22, "classes" : 2 }
{ "_id" : ObjectId("5fa943987a7deafb9e54333c"), "name" : "people23", "age" : 23, "classes" : 3 }
{ "_id" : ObjectId("5fa943987a7deafb9e54333d"), "name" : "people24", "age" : 24, "classes" : 4 }
{ "_id" : ObjectId("5fa943987a7deafb9e54333e"), "name" : "people25", "age" : 25, "classes" : 5 }
{ "_id" : ObjectId("5fa943987a7deafb9e54333f"), "name" : "people26", "age" : 26, "classes" : 6 }
{ "_id" : ObjectId("5fa943987a7deafb9e543340"), "name" : "people27", "age" : 27, "classes" : 7 }
{ "_id" : ObjectId("5fa943987a7deafb9e543341"), "name" : "people28", "age" : 28, "classes" : 8 }
{ "_id" : ObjectId("5fa943987a7deafb9e543342"), "name" : "people29", "age" : 29, "classes" : 9 }
{ "_id" : ObjectId("5fa943987a7deafb9e543343"), "name" : "people30", "age" : 30, "classes" : 10 }
{ "_id" : ObjectId("5fa943987a7deafb9e543344"), "name" : "people31", "age" : 31, "classes" : 11 }
{ "_id" : ObjectId("5fa943987a7deafb9e543345"), "name" : "people32", "age" : 32, "classes" : 12 }
{ "_id" : ObjectId("5fa943987a7deafb9e543346"), "name" : "people33", "age" : 33, "classes" : 13 }
{ "_id" : ObjectId("5fa943987a7deafb9e543347"), "name" : "people34", "age" : 34, "classes" : 14 }
{ "_id" : ObjectId("5fa943987a7deafb9e543348"), "name" : "people35", "age" : 35, "classes" : 15 }
{ "_id" : ObjectId("5fa943987a7deafb9e543349"), "name" : "people36", "age" : 36, "classes" : 16 }
{ "_id" : ObjectId("5fa943987a7deafb9e54334a"), "name" : "people37", "age" : 37, "classes" : 17 }
{ "_id" : ObjectId("5fa943987a7deafb9e54334b"), "name" : "people38", "age" : 38, "classes" : 18 }
{ "_id" : ObjectId("5fa943987a7deafb9e54334c"), "name" : "people39", "age" : 39, "classes" : 19 }
{ "_id" : ObjectId("5fa943987a7deafb9e54334d"), "name" : "people40", "age" : 40, "classes" : 0 }
Type "it" for more
> 

  提示:創建測試數據可以使用循環的方式,它這裡的循環和c語言中的循環是一樣的;在mongodb中查看數據,當數據量過多時,它不會一次性全部顯示,而是分頁顯示,每次默認顯示20條;鍵入it命令可以顯示下一頁;

  在mongodb上創建索引,語法格式:db.mycoll.ensureIndex(keypattern[,options])或者db.mycoll.createIndex(keypattern[,options])

  在name欄位上創建索引

> db.peoples.ensureIndex({name:1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
> 

  提示:這裡的name是指欄位名稱,而非索引名稱;後面的1表示升序,-1表示降序;

  查看索引

> db.peoples.getIndices()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_"
        },
        {
                "v" : 2,
                "key" : {
                        "name" : 1
                },
                "name" : "name_1"
        }
]
> 

  提示:從上面返回的結果可以看到,peoples這個集合上有兩個索引,一個名為_id_,其對應的欄位為_id,以升序的方式排列;一個名為name_1,其對應欄位為name,以升序的方式排列;默認不給索引取名,它就是欄位名後面加下劃線,再加表示升序或降序的數字;如下所示

  刪除索引

> db.peoples.dropIndex("name_1")
{ "nIndexesWas" : 3, "ok" : 1 }
> db.peoples.dropIndex("age_-1")
{ "nIndexesWas" : 2, "ok" : 1 }
> db.peoples.getIndices()
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" } ]
> 

  提示:刪除索引需要指定索引名稱,並且需要用引號引起來;

  在name欄位上構建唯一鍵索引

  提示:創建唯一鍵索引,我們只需要在創建索引時加上unique:true這個選項即可;所謂唯一鍵是指我們指定的欄位上的值必須是唯一的;如果在我們在插入對應欄位時和之前有的數據重複,此時會插入失敗;

  驗證:插入一條name欄位值為peoples23的數據,看看是否能夠插入成功呢?

  提示:可以看到當我們在name欄位上構建唯一鍵索引後,在插入name欄位有相同值的數據時,它告訴我們說插入的數據重複;不允許我們插入;說明我們創建的唯一鍵索引生效了;

  重建索引

> db.peoples.reIndex()
{
        "nIndexesWas" : 2,
        "nIndexes" : 2,
        "indexes" : [
                {
                        "v" : 2,
                        "key" : {
                                "_id" : 1
                        },
                        "name" : "_id_"
                },
                {
                        "v" : 2,
                        "unique" : true,
                        "key" : {
                                "name" : 1
                        },
                        "name" : "name_1"
                }
        ],
        "ok" : 1
}
> 

  提示:如果我們要修改索引,可以刪除重新鍵,上面的reIndex不能實現修改原有索引的屬性資訊;

  構建索引並指定為後台構建,釋放當前shell

> db.peoples.createIndex({age:-1},{background:true})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 2,
        "numIndexesAfter" : 3,
        "ok" : 1
}
> db.peoples.getIndices()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_"
        },
        {
                "v" : 2,
                "unique" : true,
                "key" : {
                        "name" : 1
                },
                "name" : "name_1"
        },
        {
                "v" : 2,
                "key" : {
                        "age" : -1
                },
                "name" : "age_-1",
                "background" : true
        }
]
> 

  刪除所有手動構建的索引

> db.peoples.dropIndexes()
{
        "nIndexesWas" : 3,
        "msg" : "non-_id indexes dropped for collection",
        "ok" : 1
}
> db.peoples.getIndices()
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" } ]
> 

  創建組合索引

> db.peoples.createIndex({name:1,age:1},{background:true})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
> db.peoples.getIndices()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_"
        },
        {
                "v" : 2,
                "key" : {
                        "name" : 1,
                        "age" : 1
                },
                "name" : "name_1_age_1",
                "background" : true
        }
]
> 

  以name欄位為條件查詢數據,看看mongodb查詢過程

> db.peoples.find({name:"people1221"}).explain()
{
        "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "testdb.peoples",
                "indexFilterSet" : false,
                "parsedQuery" : {
                        "name" : {
                                "$eq" : "people1221"
                        }
                },
                "queryHash" : "01AEE5EC",
                "planCacheKey" : "4C5AEA2C",
                "winningPlan" : {
                        "stage" : "FETCH",
                        "inputStage" : {
                                "stage" : "IXSCAN",
                                "keyPattern" : {
                                        "name" : 1,
                                        "age" : 1
                                },
                                "indexName" : "name_1_age_1",
                                "isMultiKey" : false,
                                "multiKeyPaths" : {
                                        "name" : [ ],
                                        "age" : [ ]
                                },
                                "isUnique" : false,
                                "isSparse" : false,
                                "isPartial" : false,
                                "indexVersion" : 2,
                                "direction" : "forward",
                                "indexBounds" : {
                                        "name" : [
                                                "[\"people1221\", \"people1221\"]"
                                        ],
                                        "age" : [
                                                "[MinKey, MaxKey]"
                                        ]
                                }
                        }
                },
                "rejectedPlans" : [ ]
        },
        "serverInfo" : {
                "host" : "node01.test.org",
                "port" : 27017,
                "version" : "4.4.1",
                "gitVersion" : "ad91a93a5a31e175f5cbf8c69561e788bbc55ce1"
        },
        "ok" : 1
}
>

  提示:從上面返回的結果可以看到在本次查詢是IXSCAN(索引掃描),所以查找很快就返回了;同時也顯示了索引相關的資訊;

  組合name和age欄位條件查詢,看看是否命中索引?

> db.peoples.find({$and:[{age:{$lt:80}},{name:{$gt:"people200"}}]}).explain()
{
        "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "testdb.peoples",
                "indexFilterSet" : false,
                "parsedQuery" : {
                        "$and" : [
                                {
                                        "age" : {
                                                "$lt" : 80
                                        }
                                },
                                {
                                        "name" : {
                                                "$gt" : "people200"
                                        }
                                }
                        ]
                },
                "queryHash" : "96038BC4",
                "planCacheKey" : "E71214BA",
                "winningPlan" : {
                        "stage" : "FETCH",
                        "inputStage" : {
                                "stage" : "IXSCAN",
                                "keyPattern" : {
                                        "name" : 1,
                                        "age" : 1
                                },
                                "indexName" : "name_1_age_1",
                                "isMultiKey" : false,
                                "multiKeyPaths" : {
                                        "name" : [ ],
                                        "age" : [ ]
                                },
                                "isUnique" : false,
                                "isSparse" : false,
                                "isPartial" : false,
                                "indexVersion" : 2,
                                "direction" : "forward",
                                "indexBounds" : {
                                        "name" : [
                                                "(\"people200\", {})"
                                        ],
                                        "age" : [
                                                "[-inf.0, 80.0)"
                                        ]
                                }
                        }
                },
                "rejectedPlans" : [ ]
        },
        "serverInfo" : {
                "host" : "node01.test.org",
                "port" : 27017,
                "version" : "4.4.1",
                "gitVersion" : "ad91a93a5a31e175f5cbf8c69561e788bbc55ce1"
        },
        "ok" : 1
}
>

  提示:可以看到我們組合兩個欄位做條件範圍查詢也是可以正常索引掃描;