views:

446

answers:

2

Hi 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
+2  A: 

maxDoc() won't change until you optimize the index using an IndexWriter. At the very least, you need to commit() 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 your IndexReaders read-only; 3.0 will open them read-only by default.

Andrew Duffy
+4  A: 

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

Generally it's best to use IndexWriter for deletions, unless

you must delete by document number

you need your searches to immediately reflect the deletions or

you must know how many documents were deleted for a given deleteDocuments invocation

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

Narayan
Thanks you very much sir
Sunil