標籤:
1、lucene索引的建立
1 /// <Contents> 2 /// 講list資料傳入建立索引 3 /// </Contents> 4 /// <param name="datalist"></param> 5 /// <returns></returns> 6 public bool CreateIndex(List<LuceneIndexArticle> datalist) 7 { 8 FSDirectory directory = FSDirectory.Open(new DirectoryInfo(IndexDic), new NativeFSLockFactory()); 9 IndexWriter writer = null;10 bool isUpdate = IndexReader.IndexExists(directory);11 if (isUpdate)12 {13 if (IndexWriter.IsLocked(directory))14 {15 IndexWriter.Unlock(directory);16 }17 }18 writer = new IndexWriter(IndexDic, PanGuAnalyzer, !isUpdate, IndexWriter.MaxFieldLength.LIMITED);//false表示追加(true表示刪除之前的重新寫入)19 20 foreach (LuceneIndexArticle data in datalist)21 {22 CreateIndex(writer, data);23 }24 writer.Optimize();25 writer.Close();26 return true;27 }28 public bool CreateIndex(IndexWriter writer, LuceneIndexArticle data)29 {30 try31 {32 if (data == null) return false;33 Document doc = new Document();34 Type type = data.GetType(); 35 PropertyInfo[] Propertys = type.GetProperties();36 for (int i = 0; i < Propertys.Length; i++)37 { 38 PropertyInfo pi = Propertys[i];39 string name = pi.Name;40 object objval = pi.GetValue(data, null);41 string value = objval == null ? "" : objval.ToString(); //值42 if (name == "ID")//id在寫入索引時必是不分詞,否則是模糊搜尋和刪除,會出現混亂43 {44 doc.Add(new Field(name, value, Field.Store.YES, Field.Index.NOT_ANALYZED));//id不分詞45 }46 else47 {48 doc.Add(new Field(name, value, Field.Store.YES, Field.Index.ANALYZED));49 }50 }51 writer.AddDocument(doc);52 }53 catch (System.IO.FileNotFoundException fnfe)54 {55 throw fnfe;56 }57 return true;58 }
索引存放目錄及Apsara Distributed File System設定檔存放
1 /// <Contents> 2 /// 索引存放目錄 3 /// </Contents> 4 /// <Contents> 5 /// Apsara Distributed File System分詞的設定檔 6 /// </Contents> 7 protected string PanGuXmlPath 8 { 9 get10 {11 return @"F:\DCIM\PanGu.xml";12 }13 }
1 protected string IndexDic2 {3 get4 {5 return @"F:\DCIM";6 }7 }
點擊建立索引
索引建立完畢,這些是產生的磁碟檔案。
下一節是如何從索引中檢索資料
Lucene全文檢索索引-從零開始(2)