concept delete document in category lucene

appears as: deleted document, delete documents, deleted documents, deleted documents, delete document
Lucene in Action, Second Edition

This is an excerpt from Manning's book Lucene in Action, Second Edition.

This test demonstrates the use of the hasDeletions() method to check if an index contains any documents marked for deletion.
This code shows the difference between two methods that are often mixed up: maxDoc() and numDocs(). The former returns the total number of deleted or undeleted documents in the index, whereas the latter returns the number of undeleted documents in an index. Because our index contains two documents, one of which is deleted, numDocs() returns 1 and maxDocs() returns 2.
In the method testDeleteAfterOptimize(), we force Lucene to merge index segments, after deleting one document, by optimizing the index. Then, the maxDoc() method returns 1 rather than 2, because after a delete and optimize, Lucene truly removes the deleted document. Only one document remains in the index.

You can also call expungeDeletes to explicitly reclaim all disk space consumed by deleted documents. This call merges any segments that have pending deletions. Although this will generally be a lower-cost operation than optimizing, it’s still quite costly and is likely only worthwhile when you know you’ve finished doing deletions for quite a while. In the worst case, if your deletions are scattered all over the segments so that all segments have deletions, then expungeDeletes does exactly the same thing as optimize: it merges all segments down to one. Let’s see next how IndexWriter chooses to make a new segment.

require 'solr'

# connect to the solr instance
conn = Solr::Connection.new('http://localhost:8983/solr', :autocommit => :on)

# add a document to the index
conn.add(:id => 123, :title_text => 'Lucene in Action, Second Edition')

# update the document
conn.update(:id => 123, :title_text => Ant in Action')

# print out the first hit in a query for 'action'
response = conn.query('action')
print response.hits[0]

# iterate through all the hits for 'action'
conn.query('action') do |hit|
  puts hit.inspect
end
# delete document by id
conn.delete(123)