nodejs MongoDB 索引 和 explain 的使用(11)

目錄
1、索引基礎
2、惟一索引
3、索引的一些參數.
4、使用 explain
5、 explain executionStats 查詢具體的執行時間

數據庫

1、索引基礎

  索引是對數據庫表中的一列或者多列的值進行排序的一種結構,可讓咱們查詢數據變得更快.工具

 

建立索引測試

db.user.ensureIndex({"name":1}) // 給user表 "username" 設置索引

 

獲取當前集合的索引

spa

db.user.getIndexes()

 

刪除索引的命令

code

db.user.dropIndex({"name":1})

 

建立複合索引blog

MongoDB 中,咱們一樣能夠建立複合索引,如:
數字 1 表示 username 鍵的索引按升序存儲, -1 表示 age 鍵的索引按照降序方式存儲。
排序

db.shop.ensureIndex({"name":1, "price":-1})

 

 

 

該索引被建立後,基於 name和 price的查詢將會用到該索引,或者是基於 username
的查詢也會用到該索引, 可是隻是基於 age 的查詢將不會用到該複合索引。所以能夠說,
若是想用到複合索引,必須在查詢條件中包含複合索引中的前 N 個索引列。然而若是查詢
條件中的鍵值順序和複合索引中的建立順序不一致的話, MongoDB 能夠智能的幫助咱們調
整該順序,以便使複合索引能夠爲查詢所用。如:
索引

db.shop.find({"price": 30, "name": "stephen"}) // 命中索引

 

  對於上面示例中的查詢條件, MongoDB 在檢索以前將會動態的調整查詢條件文檔的順
序,以使該查詢能夠用到剛剛建立的複合索引。

內存

  對於上面建立的索引, MongoDB 都會根據索引的 keyname 和索引方向爲新建立的索引
自動分配一個索引名, 下面的命令能夠在建立索引時爲其指定索引名,如:
rem

db.shop.ensureIndex({"name":1},{"name":"userindex"})  // 制定索引名 userindex

  

  隨着集合的增加,須要針對查詢中大量的排序作索引。若是沒有對索引的鍵調用 sort
MongoDB 須要將全部數據提取到內存並排序。所以在作無索引排序時,若是數據量過大以
致沒法在內存中進行排序,此時 MongoDB 將會報錯 .

2、惟一索引

  在缺省狀況下建立的索引均不是惟一索引。下面的示例將建立惟一索引,如:

db.user.ensureIndex({"userid":1},{"unique":true}) //建立惟一索引

  

  若是再次插入 userid 重複的文檔時, MongoDB 將報錯,以提示插入重複鍵,如:

db.user.insert({"userid":5})
db.user.insert({"userid":5})

 

報錯信息: 惟一索引不能重複

  E11000 duplicate key error index: user.user.$userid_1 dup key: { : 5.0 }

  若是插入的文檔中不包含 userid 鍵,那麼該文檔中該鍵的值爲 null,若是屢次插入相似
的文檔, MongoDB 將會報出一樣的錯誤,如:

db.user.insert({"userid1":5})
db.user.insert({"userid1":5})

 

報錯信息: 惟一索引不能爲 null
  E11000 duplicate key error index: user.user.$userid_1 dup key: { : null }

  若是在建立惟一索引時已經存在了重複項,咱們能夠經過下面的命令幫助咱們在建立惟
一索引時消除重複文檔,僅保留髮現的第一個文檔,如:

db.user.dropIndex({"userid":1})

 

插入測試數據,以保證集合中有重複鍵存在。

db.user.remove()
db.user.insert({"userid":5})
db.user.insert({"userid":5})

 

從新建立惟一索引

db.user.ensureIndex({"userid":1},{"unique":true }}

 

 

 

 

三 索引的一些參數

 

 

mongo 後臺創建索引

db.user.ensureIndex({"username":1},{"background":true})

 

4、使用 explain

  explain 是很是有用的工具,會幫助你得到查詢方面諸多有用的信息。只要對遊標調用
該方法,就能夠獲得查詢細節。 explain 會返回一個文檔,而不是遊標自己。如:

 

 

explain 會返回查詢使用的索引狀況,耗時和掃描文檔數的統計信息。

 

5、 explain executionStats 查詢具體的執行時間 

語法:

db.tablename.find().explain( "executionStats" )
關注輸出的以下數值: explain.executionStats.executionTimeMillis

 

構建大量數據:

for (var i =1;i<1000000;i++){db.user.insert({"name":"zhangsan"+i,"age":"5",'num':i})}

 

不加索引,查詢時間

{
    ...
        },
        "executionStats" : {
                "executionSuccess" : true,
                "nReturned" : 1,
                "executionTimeMillis" : 695,
               ...
}

 

添加索引,查詢時間

{
    ...
        },
        "executionStats" : {
                "executionSuccess" : true,
                "nReturned" : 1,
                "executionTimeMillis" : 88,
               ...
}
相關文章
相關標籤/搜索