Luceneインデックスからドキュメントを検索して削除するメソッドがあります。
ただし、コードを2回実行すると、前の反復から削除するようにマークされたドキュメントが検出され、indexReader.hasDeletions()がtrueと評価されます。
public void duplicatesRemover(String currentIndex) throws Exception {
Directory directory = FSDirectory.open(new File(currentIndex));
IndexReader indexReader = IndexReader.open(directory, false);
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
int dups = 0;
for (int i = 0; i < indexReader.numDocs(); i++) {
Document doc = indexReader.document(i);
int articleId = Integer.parseInt(doc.get("articleId"));
Query q = NumericRangeQuery.newIntRange("articleId", articleId, articleId, true, true);
TopDocs topDocs = indexSearcher.search(q, 10);
if (topDocs.totalHits > 1 ) {
indexReader.deleteDocument(i);
System.out.print("Total matches from search found: " + topDocs.totalHits + " articleId = " + articleId);
System.out.println(" total dups found " + ++dups + "/" + i);
}
}
if(indexReader.hasDeletions()){
System.out.println("Has deletions");
Map<String, String> commitUserData = new HashMap<String, String>();
commitUserData.put("foo", "fighter");
indexReader.commit(commitUserData);
}
indexSearcher.close();
indexReader.close();
directory.close();
}
ヨギありがとう