I want to delete a document in lucene 2.4 with java. My code is
Directory directory = FSDirectory.getDirectory("c:/index");
IndexReader indexReader = IndexReader.open(directory);
System.out.println("num="+indexReader.maxDoc());
indexReader.deleteDocuments(new Term("name","1"));
System.out.println("num="+indexReader.maxDoc());
output
num=1
num=1
maxDoc()
won't change until you optimize the index using anIndexWriter
. At the very least, you need tocommit()
or your delete may never even make it to disk.However,
numDocs()
should return the number of non-deleted documents even before a commit or optimize.It's probably better practice (and certainly less confusing) to use an
IndexWriter
to add and delete documents and to open yourIndexReader
s read-only; 3.0 will open them read-only by default.In my opinion it is best to use Indexwriter to delete the documents, since Indexreader buffers the deletions and does not write changes to the index until close() is called on.; unless you use the same reference for search.
The Lucene wiki states
I can see you want the maxdoc value for the document in memory so its a better approach to use Indexwriter
so the answer for your question is
you should close the Indexreader object or use Indexwriter for deletions