MongoDB 創建基礎索引、組合索引、唯一索引以及優化

一、索引

MongoDB 提供了多樣性的索引支持,索引信息被保存在system.indexes 中,且默認總是爲_id創建索引,它的索引使用基本和MySQL 等關係型數據庫一樣。其實可以這樣說說,索引是凌駕於數據存儲系統之上的另一層系統,所以各種結構迥異的存儲都有相同或相似的索引實現及使用接口並不足爲 奇。

基礎索引

在字段age 上創建索引,1(升序);-1(降序):

db.users.ensureIndex({age:1})

_id 是創建表的時候自動創建的索引,此索引是不能夠刪除的。當系統已有大量數據時,創建索引就是個非常耗時的活,我們可以在後臺執行,只需指定“backgroud:true”即可。

db.users.ensureIndex({age:1} , {backgroud:true})

文檔索引

索引可以任何類型的字段,甚至文檔:

db.factories.insert( { name: "wwl", addr: { city: "Beijing", state: "BJ" } } );

在addr 列上創建索引

db.factories.ensureIndex( { addr : 1 } );

下面這個查詢將會用到我們剛剛建立的索引

db.factories.find( { addr: { city: "Beijing", state: "BJ" } } );

但是下面這個查詢將不會用到索引,因爲查詢的順序跟索引建立的順序不一樣

db.factories.find( { addr: { state: "BJ" , city: "Beijing"} } );

組合索引

跟其它數據庫產品一樣,MongoDB 也是有組合索引的,下面我們將在addr.city 和addr.state上建立組合索引。當創建組合索引時,字段後面的1 表示升序,-1 表示降序,是用1 還是用-1 主要是跟排序的時候或指定範圍內查詢 的時候有關的。

db.factories.ensureIndex( { "addr.city" : 1, "addr.state" : 1 } );

下面的查詢都用到了這個索引

db.factories.find( { "addr.city" : "Beijing", "addr.state" : "BJ" } );

db.factories.find( { "addr.city" : "Beijing" } );

db.factories.find().sort( { "addr.city" : 1, "addr.state" : 1 } );

db.factories.find().sort( { "addr.city" : 1 } );

唯一索引

只需在ensureIndex 命令中指定”unique:true”即可創建唯一索引。例如,往表t4 中插入2 條記錄時候報錯。

db.t4.ensureIndex({firstname: 1, lastname: 1}, {unique: true});

強制使用索引

hint 命令可以強制使用某個索引。

db.t5.find({age:{$lt:30}}).hint({name:1, age:1}).explain()

刪除索引

刪除t3 表中的所有索引

db.t3.dropIndexes()

刪除t4 表中的firstname 索引

db.t4.dropIndex({firstname: 1})

二、explain執行計劃

MongoDB 提供了一個 explain 命令讓我們獲知系統如何處理查詢請求。利用 explain 命令,我們可以很好地觀察系統如何使用索引來加快檢索,同時可以針對性優化索引。

db.sang_collect.find({x:1}).explain()
# 返回值, 在python中運行
{
    "queryPlanner" : {
        "plannerVersion" : 1,
        "namespace" : "sang.sang_collect",
        "indexFilterSet" : false,
        "parsedQuery" : {
            "x" : {
                "$eq" : 1.0
            }
        },
        "winningPlan" : {
            "stage" : "COLLSCAN",
            "filter" : {
                "x" : {
                    "$eq" : 1.0
                }
            },
            "direction" : "forward"
        },
        "rejectedPlans" : []
    },
    "serverInfo" : {
        "host" : "localhost.localdomain",
        "port" : 27017,
        "version" : "3.4.9",
        "gitVersion" : "876ebee8c7dd0e2d992f36a848ff4dc50ee6603e"
    },
    "ok" : 1.0
}

MongoDB 創建基礎索引、組合索引、唯一索引以及優化
MongoDB 創建基礎索引、組合索引、唯一索引以及優化
字段說明:
MongoDB 創建基礎索引、組合索引、唯一索引以及優化

executionStats

executionStats會返回最佳執行計劃的一些統計信息,如下:

db.sang_collect.find({x:1}).explain('executionStats')

{
    "queryPlanner" : {
        "plannerVersion" : 1,
        "namespace" : "sang.sang_collect",
        "indexFilterSet" : false,
        "parsedQuery" : {},
        "winningPlan" : {
            "stage" : "COLLSCAN",
            "direction" : "forward"
        },
        "rejectedPlans" : []
    },
    "executionStats" : {
        "executionSuccess" : true,
        "nReturned" : 10000,
        "executionTimeMillis" : 4,
        "totalKeysExamined" : 0,
        "totalDocsExamined" : 10000,
        "executionStages" : {
            "stage" : "COLLSCAN",
            "nReturned" : 10000,
            "executionTimeMillisEstimate" : 0,
            "works" : 10002,
            "advanced" : 10000,
            "needTime" : 1,
            "needYield" : 0,
            "saveState" : 78,
            "restoreState" : 78,
            "isEOF" : 1,
            "invalidates" : 0,
            "direction" : "forward",
            "docsExamined" : 10000
        }
    },
    "serverInfo" : {
        "host" : "localhost.localdomain",
        "port" : 27017,
        "version" : "3.4.9",
        "gitVersion" : "876ebee8c7dd0e2d992f36a848ff4dc50ee6603e"
    },
    "ok" : 1.0
}

這裏除了我們上文介紹到的一些參數之外,還多了executionStats參數,含義如下:
MongoDB 創建基礎索引、組合索引、唯一索引以及優化

三、優化器profile

在MySQL 中,慢查詢日誌是經常作爲我們優化數據庫的依據,那在MongoDB 中是否有類似的功能呢?答案是肯定的,那就是MongoDB Database Profiler。

開啓profiling功能

有兩種方式可以控制 Profiling 的開關和級別,第一種是直接在啓動參數裏直接進行設置。啓動MongoDB 時加上–profile=級別 即可。也可以在客戶端調用db.setProfilingLevel(級別) 命令來實時配置,Profiler 信息保存在system.profile 中。我們可以通過db.getProfilingLevel()命令來獲取當前的Profile 級別,類似如下操作:

db.setProfilingLevel(2);

上面profile 的級別可以取0,1,2 三個值,他們表示的意義如下:

0 – 不開啓

1 – 記錄慢命令 (默認爲>100ms)

2 – 記錄所有命令

Profile 記錄在級別1 時會記錄慢命令,那麼這個慢的定義是什麼?上面我們說到其默認爲100ms,當然有默認就有設置,其設置方法和級別一樣有兩種,一種是通過添加 –slowms 啓動參數配置。第二種是調用db.setProfilingLevel 時加上第二個參數:

db.setProfilingLevel( level , slowms )

db.setProfilingLevel( 1 , 10 );

查詢 Profiling 記錄

與MySQL 的慢查詢日誌不同,MongoDB Profile 記錄是直接存在系統db 裏的,記錄位置system.profile ,所以,我們只要查詢這個Collection 的記錄就可以獲取到我們的 Profile 記錄了。列出執行時間長於某一限度(5ms)的 Profile 記錄:

db.system.profile.find( { millis : { $gt : 5 } } )

MongoDB Shell 還提供了一個比較簡潔的命令show profile,可列出最近5 條執行時間超過1ms 的 Profile 記錄。

四、常用性能優化方案

創建索引, 當查詢的字段有2個時,數據量較大時,可以使用聯合索引

限定返回結果數

只查詢使用到的字段

採用capped collection

採用Server Side Code Execution

使用Hint,強制使用索引

採用Profiling

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章