MongoDB string欄位索引方案

來源:互聯網
上載者:User


在研究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);
 
}

最後執行程式查看結果:  

多次測試表明在有索引的情況下,查詢效率要高於無索引的效率。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.