在研究MongoDB的索引是發現一個奇怪的問題,給一個string類型的field設定 text索引 ,但是在查詢的時候並沒有使用索引。比如:
db.tomcat_access_logs.ensureIndex( { url : 'text' });
db.tomcat_access.logs.find( { url : '1' } ).explain();
db.tomcat_access_logs.find( { url : /1/ } ).explain();
{
"cursor" : "BasicCursor",
"isMultiKey" : false,
"n" : 0,
"nscannedObjects" : 100,
"nscanned" : 100,
"nscannedObjectsAllPlans" : 100,
"nscannedAllPlans" : 100,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
...
}
從 explain() 的結果可以發現,在查詢的時候只用了 BasicCursor ,也就是說沒有使用索引。
後發現只有當使用 $text 查詢的時候才會用到 text索引 :
db.tomcat_access_logs.find( { $text : { $search : '1'} } ).explain();
{
"cursor" : "TextCursor",
"n" : 0,
"nscannedObjects" : 0,
"nscanned" : 0,
"nscannedObjectsAllPlans" : 0,
"nscannedAllPlans" : 0,
"scanAndOrder" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
...
}
只不過這樣的話,就沒有辦法針對某個特定field進行查詢了,因為 $text 是對所有 text索引 的field進行的全文檢索搜尋。此時只需要做一般的索引即可:
db.tomcat_access_logs.ensureIndex( { url : 1 } );
db.tomcat_access.logs.find( { url : '1' } ).explain();
db.tomcat_access.logs.find( { url : /.*1.*/g } ).explain();
{
"cursor" : "BtreeCursor url_1",
"isMultiKey" : false,
"n" : 0,
"nscannedObjects" : 0,
"nscanned" : 100,
"nscannedObjectsAllPlans" : 0,
"nscannedAllPlans" : 100,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 1,
"indexBounds" : {
"url" : [
[
"",
{
}
],
[
/.*1.*/,
/.*1.*/
]
]
},
...
}
總結
使用 db.collection.find( { url : '1'} ) 或者 db.collection.find( { url : /.*a.*/} ) ,不會使用的text索引,而是一般索引。
建立了text索引後,只能對text索引包含的所有欄位進行全文檢索搜尋,無法對某個欄位進行搜尋
一般索引和text索引可以同時建立,以滿足不同查詢需求
索引的效率
MongoDB的索引到底能不能提高查詢效率呢?我們在這裡通過一個例子來測試。比較同樣的資料在無索引和有索引的情況下的查詢速度。
首先,我們通過這樣一個方法插入10W條資料:
public void InsertBigData()
{
var random = new Random();
for (int i = 1; i < 100000; i++)
{
Document doc = new Document();
doc["ID"] = i;
doc["Data"] = "data" + random.Next(100000);
mongoCollection.Save(doc);
}
Console.WriteLine("當前有" + mongoCollection.FindAll().Documents.Count() + "條資料");
}
然後,實現一個方法用來建立索引:
public void CreateIndexForData()
{
mongoCollection.Metadata.CreateIndex(new Document { { "Data", 1 } }, false);
}
還有排序的方法:
public void SortForData()
{
mongoCollection.FindAll().Sort(new Document { { "Data", 1 } });
}
運行測試代碼如下:
static void Main(string[] args)
{
IndexBLL indexBll = new IndexBLL();
indexBll.DropAllIndex();
indexBll.DeleteAll();
indexBll.InsertBigData();
Stopwatch watch1 = new Stopwatch();
watch1.Start();
for (int i = 0; i < 1; i++) indexBll.SortForData();
Console.WriteLine("無索引排序執行時間:" + watch1.Elapsed);
indexBll.CreateIndexForData();
Stopwatch watch2 = new Stopwatch();
watch2.Start();
for (int i = 0; i < 1; i++) indexBll.SortForData();
Console.WriteLine("有索引排序執行時間:" + watch2.Elapsed);
}
最後執行程式查看結果:
多次測試表明在有索引的情況下,查詢效率要高於無索引的效率。