我有一個類似於在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的抱怨重命名「可刪除」的文件?
IndexFileLocation.List()。只有在沒有索引文件存在的情況下,長度== 0將計算爲true – Roman 2010-07-25 12:41:57