Reputation: 97
I'm trying to build an operation of Index by using Lucene.Net, and I was testing the code step by step,
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();
}
I realized that after the request passed over Delete documents method, the document still exists, writer.deletedocuments is not working, I also tried to add Flush and commit, it's still not working.What should I do in this case?
Upvotes: 2
Views: 702
Reputation: 6991
It's not clean how you do Search, so my same issue was solved by:
writer.Flush(...)
(you did)writer.Commit()
(this line is commented in your code)_searchManager.MaybeRefreshBlocking();
(recommended)In code:
writer.Flush(true, true);
writer.Commit();
and then, in new search:
_searchManager.MaybeRefreshBlocking();
var searcher = _searchManager.Acquire();
try
{
var topDocs = searcher.Search(query, 10);
// ... do your search logic here ...
}
finally
{
_searchManager.Release(searcher);
searcher = null;
}
Upvotes: 1
Reputation: 781
Try this way to delete your documents you can also pass your directory object to the ClearLuceneIndexRecord
method as parameter.
public static void ClearLuceneIndexRecord(int record_id)
{
// init lucene
var analyzer = new PanGuAnalyzer();
using (var writer = new IndexWriter(_directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED))
{
// remove older index entry
var DocIdToDelete= new TermQuery(new Term("id", record_id.ToString()));
writer.DeleteDocuments(DocIdToDelete);
// close handles
analyzer.Close();
writer.Dispose();
}
}
Hope it will help you!
Upvotes: 2