標籤:mongodb 索引
MongoDB的索引和關係型資料庫的索引概念和功能是相同的:
(1)不使用索引的搜尋可以稱為全表掃面,也就是說,伺服器必須找完整個表才能查詢整個結果;
(2)建立索引後搜尋,查詢在索引中搜尋,在索引的條目中找到條目以後,就可以直接跳轉到目的文件的位置;這樣的搜尋比全表的搜尋的速度要提高好幾個數量級;
先向集合blog中添加1000000個文檔:
> for (i=0;i<1000000;i++){ ... db.users.insert( ... {"i":i, ... "username":"user"+1, ... "age":Math.floor(Math.random()*120), ... "created":new Date()});} WriteResult({ "nInserted" : 1 }) >
在上述的集合中隨機查詢一個文檔,使用explain函數來查看搜尋過程中的資訊:
> db.users.find({"username":"user101"}).explain() { "cursor" : "BasicCursor", "isMultiKey" : false, "n" : 1, "nscannedObjects" : 1000000, "nscanned" : 1000000, "nscannedObjectsAllPlans" : 1000000, "nscannedAllPlans" : 1000000, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 7812, "nChunkSkips" : 0, "millis" : 344, "server" : "localhost.localdomain:27017", "filterSet" : false } >
其中millies指明搜尋花費的毫秒數為344毫秒;
其中n代表掃描全表後的搜尋後的結果數為1,搜尋並不知道username為user101的數量到底有幾個,為最佳化查詢將查詢的結果限制為1個,這樣在找到第一個文檔後便停止搜尋:
> db.users.find({"username":"user101"}).limit(1).explain() { "cursor" : "BasicCursor", "isMultiKey" : false, "n" : 1, "nscannedObjects" : 102, "nscanned" : 102, "nscannedObjectsAllPlans" : 102, "nscannedAllPlans" : 102, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 0, "nChunkSkips" : 0, "millis" : 0, "server" : "localhost.localdomain:27017", "filterSet" : false } >
可以看到millis為0,因為掃描文檔的數量極大減少了,查詢幾乎瞬間完成;
但是這個方法有缺陷,如果找users999999,仍然幾乎掃描整個集合。
> db.users.find({"username":"user999999"}).limit(1).explain() { "cursor" : "BasicCursor", "isMultiKey" : false, "n" : 1, "nscannedObjects" : 1000000, "nscanned" : 1000000, "nscannedObjectsAllPlans" : 1000000, "nscannedAllPlans" : 1000000, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 7812, "nChunkSkips" : 0, "millis" : 321, "server" : "localhost.localdomain:27017", "filterSet" : false } >
花費幾乎和搜尋整個集合的的時間millis差不多為321,而且隨著文檔數量增加,查詢花費的時間越長;
在username欄位上建立索引:
> db.users.ensureIndex({"username":1}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } >
重新查詢users999999的使用者:
> db.users.find({"username":"user999999"}).limit(1).explain() { "cursor" : "BtreeCursor username_1", "isMultiKey" : false, "n" : 1, "nscannedObjects" : 1, "nscanned" : 1, "nscannedObjectsAllPlans" : 1, "nscannedAllPlans" : 1, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 0, "nChunkSkips" : 0, "millis" : 85, "indexBounds" : { "username" : [ [ "user999999", "user999999" ] ] }, "server" : "localhost.localdomain:27017", "filterSet" : false } >
花費的時間millis為85,比沒有建立索引前的321要少很多;
當然索引會加快查詢的速度,但是也有弊端,每次添加、刪除、更新一個文檔,MongoDB不僅要更新文檔,還要更新文檔上的索引;
每個集合只能有64個集合,挑選合適的欄位建立索引非常重要。
本文出自 “緣隨心愿” 部落格,請務必保留此出處http://281816327.blog.51cto.com/907015/1600482
【MongoDB學習筆記20】MongoDB的索引