2010-07-24 66 views
0

我有一個類似於在Asp.net MVC中編寫的web應用程序的論壇。我試圖將Lucene.net作爲搜索引擎。當我構建我的索引時,我偶爾會遇到與Lucene相關的異常,無法重命名deletable文件。我想這是因爲我每次要重建索引時都會清空索引。下面是與索引交易代碼:什麼是重建Lucene的索引的正確方法

public class SearchService : ISearchService 
{ 
    Directory IndexFileLocation; 
    IndexWriter Writer; 
    IndexReader Reader; 
    Analyzer Analyzer; 

    public SearchService(String indexLocation) 
    { 
     IndexFileLocation = FSDirectory.GetDirectory(indexLocation, System.IO.Directory.Exists(indexLocation) == false); 
     Reader   = IndexReader.Open(IndexFileLocation); 
     Writer   = new IndexWriter(IndexFileLocation, Analyzer, IndexFileLocation.List().Length == 0); 
     Analyzer   = new StandardAnalyzer(); 
    } 

    public void ClearIndex() 
    { 
     var DocumentCount = Writer.DocCount(); 
     if (DocumentCount == 0) 
      return; 

     for (int i = 0; i < DocumentCount; i++) 
      Reader.DeleteDocument(i); 
    } 

    public void AddToSearchIndex(ISearchableData Data) 
    { 
     Document Doc = new Document(); 

     foreach (var Entry in Data) 
     { 
      Field field = new Field(Entry.Key, 
            Entry.Value, 
            Lucene.Net.Documents.Field.Store.NO, 
            Lucene.Net.Documents.Field.Index.TOKENIZED, 
            Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS); 
      Doc.Add(field); 
     } 

     Field KeyField = new Field(
      SearchField.Key.ToString(), 
      Data.Key, 
      Lucene.Net.Documents.Field.Store.YES, 
      Lucene.Net.Documents.Field.Index.NO); 

     Doc.Add(KeyField); 
     Writer.AddDocument(Doc); 
    } 

    public void Dispose() 
    { 
     Writer.Optimize(); 
     Writer.Close(); 
     Reader.Close(); 
    } 
} 

這裏是執行它的所有代碼:

private void btnRebuildIndex_Click(object sender, EventArgs e) 
    { 
     using (var SearchService = new SearchService(Application.StartupPath + @"\indexs\")) 
     { 
      SearchService.ClearIndex(); 
     } 

     using (var SearchService = new SearchService(Application.StartupPath + @"\indexs\")) 
     { 
      Int32 BatchSize = 50; 
      Int32 Current = 0; 
      var TotalQuestions = SubmissionService.GetQuestionsCount(); 

      while (Current < TotalQuestions) 
      { 
       var Questions = SubmissionService.ListQuestions(Current, BatchSize, "Id", Qsparx.SortOrder.Asc); 

       foreach (var Question in Questions) 
       { 
        SearchService.AddToSearchIndex(Question.ToSearchableData()); 
       } 

       Current += BatchSize; 
      } 
     } 
    } 

爲什麼Lucene的抱怨重命名「可刪除」的文件?

回答

0

事實證明,如果沒有索引文件存在,那麼在IndexWriter之前創建IndexReader並不是一個好主意。我也意識到,即使IndexWriter的AddDocument方法有兩個重載(一個w /和一個w/o分析器參數),只有具有分析器參數的那個方法適用於我。

2

不確定爲什麼每次都重新創建索引。您可以追加,從而索引:

Writer = new IndexWriter(IndexFileLocation, Analyzer,false); 

末假標誌告訴的IndexWriter打開追加模式(即不覆蓋)。 這可能會導致您的問題消失。

+0

IndexFileLocation.List()。只有在沒有索引文件存在的情況下,長度== 0將計算爲true – Roman 2010-07-25 12:41:57

相關問題