mongodb索引


Note:mongodb的索引算法主要是btree和hash算法,mongodb默認采用的是btree索引算法。

1、索引

(a)索引提高查詢速度,降低寫入速度,權衡常用的查詢字段,不必在太多列上建索引

(b)在mongodb中,索引可以按字段升序/降序來創建,便於排序

(c)默認是用btree來組織索引文件,2.4版本以后,也允許建立hash索引.

 

2、索引分類

普通索引({field:1/-1})
唯一索引({filed.subfield:1/-1}, {unique:true})
稀疏索引({field:1/-1},{sparse:true})
哈希索引({file:'hashed'})

 

3、常用索引命令:

#查看查詢計划
db.collection.find(query).explain();
    "cursor" : "BasicCursor", ----說明沒有索引發揮作用
    "nscannedObjects" : 1000 ---理論上要掃描多少行
    cursor" : "BtreeCursor sn_1", 用到的btree索引
eg:db.shop.find({age:33}).explain();


#查看當前索引狀態
db.collection.getIndexes();
eg:db.shop.getIndexes();

#創建普通的單列索引,1是升續 2是降序
db.collection.ensureIndex({field:1/-1});  
eg:db.shop.ensureIndex({age:1});

#刪除單個索引
db.collection.dropIndex({filed:1/-1});
eg:db.shop.dropIndex({age:1});

#刪除所有索引
db.collection.dropIndexes();
eg:db.shop.dropIndexes();

#創建多列索引  
db.collection.ensureIndex({field1:1/-1, field2:1/-1});
eg:db.shop.ensureIndex({age:1,name:1});

#創建子文檔索引
db.collection.ensureIndex({filed.subfield:1/-1});
eg:db.test.ensureIndex({"feature.age":1})
#根據子文檔索引查找
eg:db.test.find({"feature.age":22})

#創建唯一索引
db.collection.ensureIndex({filed.subfield:1/-1}, {unique:true});
eg:db.test.ensureIndex({name:1},{unique:true})

#創建稀疏索引
db.collection.ensureIndex({field:1/-1},{sparse:true});
eg:db.test.ensureIndex({name:1},{sparse:true})
稀疏索引的特點:如果針對field做索引,針對不含field列的文檔,將不建立索引.
與之相對,普通索引,會把該文檔的field列的值認為NULL,並建索引.
應用場景:小部分文檔含有某列時.

#創建哈希索引(2.4新增的)
db.collection.ensureIndex({file:'hashed'});
eg:db.test.ensureIndex({name:'hashed'});
哈希索引速度比普通索引快,但是,無法對范圍查詢進行優化.
適宜於:隨機性強的散列

#重建索引
db.collection.reIndex()
eg:db.test.reIndex();
一個表經過很多次修改后,導致表的文件產生空洞,索引文件也如此.
可以通過索引的重建,減少索引文件碎片,並提高索引的效率.
類似mysql中的optimize table

后續有應用,將繼續補充,同時歡迎大家留言,一起學習、進步。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM