Lucene.net仅包含最后添加的文档

时间:2010-04-14 10:07:54

标签: .net asp.net-mvc lucene.net

这是一个奇怪的问题,但每次我向Lucene.net添加一个新文档时,它会覆盖最后一个文档,因此它始终保存最后插入的文档。我已经使用LUKE确认了这种行为,它允许我打开索引文件。如果有人能够解决这个问题,我会很感激。这是我的代码:

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>();

1 个答案:

答案 0 :(得分:0)

此处true

new IndexWriter(indexFileLocation, analyzer, true);

告诉Lucene创建一个新索引,删除旧索引。