0
這是一個奇怪的問題,但每次向Lucene.net添加新文檔時,它都會覆蓋最後一個文檔,因此它始終保存最後插入的文檔。我已經使用LUKE證實了這種行爲,它可以讓我打開索引文件。如果有人能夠解決這個問題,我將不勝感激。這裏是我的代碼:Lucene.net只包含最後添加的文檔
public class SearchService : ISearchService
{
Directory indexFileLocation;
Analyzer analyzer;
public SearchService(String indexLocation)
{
indexFileLocation = FSDirectory.GetDirectory(indexLocation, true);
analyzer = new StandardAnalyzer();
}
public void AddToSearchIndex(ISearchableData data)
{
IndexWriter indexWriter = new IndexWriter(indexFileLocation, analyzer, true);
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.UN_TOKENIZED);
doc .Add(keyField);
indexWriter.AddDocument(doc);
indexWriter.Optimize();
indexWriter.Close();
}
public IDictionary<Int32, float> SearchContent(String term)
{
IndexSearcher searcher = new IndexSearcher(indexFileLocation);
TermQuery query = new TermQuery(new Term(SearchField.Content.ToString(), term));
Hits hits = searcher.Search(query);
searcher.Close();
return OrganizeSearchResults(hits);
}
public IDictionary<Int32, float> OrganizeSearchResults(Hits hits)
{
IDictionary<Int32, float> result = new Dictionary<Int32, float>();
String keyField = SearchField.Key.ToString();
for (int i = 0; i < hits.Length(); i++)
{
Document doc = hits.Doc(i);
Field field = doc.GetField(keyField);
result.Add(Int32.Parse(
field.StringValue()),
hits.Score(i));
}
return result;
}
}
我添加的文件是這樣的:
new SearchService(searchIndexFolderPath).AddToSearchIndex(entry.ToSearchableData());
和搜索這樣的:
ISearchService search = new SearchService(MvcApplication.SearchIndexPath);
IList<Int32> submissionIds = search.SearchContent(SearchTerm).Select(hit => hit.Key).ToList<Int32>();
感謝您的回覆。如果這總是錯誤的,或者我應該根據目錄是否已經索引數據來有條件地傳遞這個值? – Roman 2010-04-14 10:17:11
你需要用'true'來調用它來創建索引。你可以在你的文檔添加代碼的單獨代碼中做到這一點 - 這是'indexWriter = new IndexWriter(...,true); indexWriter.Close()'只是爲了創建索引,然後在'indexWriter = new IndexWriter(...,false);'寫入它。 – RichieHindle 2010-04-14 10:32:55
嘗試了你的建議並且像魅力一樣工作: Boolean createNewIndexFile = indexFileLocation.List()。Length == 0; IndexWriter indexWriter = new IndexWriter(indexFileLocation,analyzer,createNewIndexFile); – Roman 2010-04-14 10:35:04