Lucene.Net 建立索引

摘要:Lucene.Net 建立索引

當我們在使用 IndexWriter 建立索引的時候 , 該類別提供了兩個方式 , 

 

一個是會重新建立索引 , 另外一個方式是會直接附加在現有的 Index 後  

 

How to  Build Index :

 


public void BuildIndex()
    {
        DirectoryInfo dirInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory.ToString() + "\\App_Data");
        FSDirectory dir = FSDirectory.Open(dirInfo);
        //create 參數(第三個參數) , 若設定 false 就會累加上去 , 若 true 則會重新建立
        IndexWriter iw = new IndexWriter(dir, new StandardAnalyzer(Version.LUCENE_30), true, IndexWriter.MaxFieldLength.UNLIMITED);

        Document doc = new Document();
        doc.Add(new Field("PROD_ID", "", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO));
        doc.Add(new Field("PROD_Name", "", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO));
       
        for (int i = 1; i <= 10; i++)
        {
            doc.GetField("PROD_ID").SetValue(Guid.NewGuid().ToString());
            doc.GetField("PROD_Name").SetValue("Lucene.Net" + i.ToString());
            iw.AddDocument(doc);
        }
        iw.Optimize();
        iw.Commit();
        iw.Close();
    }

 

 

IndexWriter 共有 4 個參數 , 依序為

一. Directory , Lucene 內部的一種目錄表示方式

二. Analyzer ,  Lucene 中負責對各種資料來源進行過濾 , 分詞

三. create 參數 , 是否要覆寫現在的 Index 檔案 , 若 false , 表示 append 目前的 Index 檔案

四. mfl 參數 , 表示字彙最大長度

 

IndexWriter.optimize() 索引最佳化:

對所指定的索引目錄下所有的 segment 做最佳化 , 使所有的 segments 合併成一個完整的segment  , 

對檢索時效率的提升是很大的幫助 , 因為在檢索時需要開啟每個索引檔案 , 若此時索引檔案很多 , 

那麼開啟這麼多的檔案對於系統的資源消耗很大