C#Lucene.Net IndexWriter.DeleteDocuments无法正常工作

时间:2017-05-25 13:15:10

标签: c# lucene.net

我正在尝试使用Lucene.Net构建一个Index操作,我正在逐步测试代码,

private void CRUDIndex()
    {


        FSDirectory directory = FSDirectory.Open(new DirectoryInfo(Path), new NativeFSLockFactory());


        bool isExist = IndexReader.IndexExists(directory);
        if (isExist)
        {
            if (IndexWriter.IsLocked(directory))
            {
                IndexWriter.Unlock(directory);
            }
        }
        IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isExist, IndexWriter.MaxFieldLength.UNLIMITED);
        while (bookQueue.Count > 0)
        {
if (book.IT == IndexType.Insert)
            {
                document.Add(new Field("id", book.ID.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
                document.Add(new Field("title", book.Title, Field.Store.YES, Field.Index.ANALYZED,
                                       Field.TermVector.WITH_POSITIONS_OFFSETS));
                document.Add(new Field("content", book.Starring, Field.Store.YES, Field.Index.ANALYZED,
                                       Field.TermVector.WITH_POSITIONS_OFFSETS));
                writer.AddDocument(document);
            }
            else if (book.IT == IndexType.Delete)
            {


                writer.DeleteDocuments(new Term("id", book.ID.ToString()));
                writer.Optimize();
                //writer.Commit();
                writer.Flush(true, true, true);
                //writer.Dispose();
            }
}
        writer.Dispose();
        directory.Dispose();
    }

我意识到在请求通过删除文档方法之后,文档仍然存在,writer.deletedocuments不能正常工作,我也尝试添加Flush并提交,它仍然无法工作。在这种情况下我该怎么办? / p>

2 个答案:

答案 0 :(得分:1)

尝试这种方式删除文档,您也可以将目录对象作为参数传递给$方法。

ClearLuceneIndexRecord

希望它会对你有所帮助!

答案 1 :(得分:0)

搜索的方式不干净,因此我的相同问题已通过以下方式解决:

  1. 使用writer.Flush(...) (您确实这么做了)
  2. 提交所有索引更改:writer.Commit() (此行在您的代码中已注释)
  3. 致电:_searchManager.MaybeRefreshBlocking(); (推荐)

在代码中:

    writer.Flush(true, true);
    writer.Commit();

然后在新搜索中:

    _searchManager.MaybeRefreshBlocking();

    var searcher = _searchManager.Acquire();
    try
    {
        var topDocs = searcher.Search(query, 10);

        // ... do your search logic here ...
    }
    finally
    {
        _searchManager.Release(searcher);
        searcher = null;
    }