简体   繁体   中英

Concurrent Read & Write in Lucene

I have an application that needs to be able to read and write a search index concurrently. What I noticed with lucene is that you can't use IndexWriter and DirectoryReader concurrently. Basically:

IndexWriter writer = new IndexWriter(directory, config);
//Add documents here...
writer.commit();

DirectoryReader reader = DirectoryReader.open(writer.getDirectory());
IndexSearcher searcher = new IndexSearcher(reader);     
QueryParser qp = new QueryParser(Version.LUCENE_46,"field", new StandardAnalyzer(Version.LUCENE_46));
qp.setAllowLeadingWildcard(true);
Query q = qp.parse("field:*");

works fine, while

IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_46, new StandardAnalyzer(Version.LUCENE_46));
IndexWriter writer = new IndexWriter(directory, config);
writer.commit();
DirectoryReader reader = DirectoryReader.open(writer.getDirectory());

//Add documents here

writer.commit();
IndexSearcher searcher = new IndexSearcher(reader);     
QueryParser qp = new QueryParser(Version.LUCENE_46,"field", new StandardAnalyzer(Version.LUCENE_46));
qp.setAllowLeadingWildcard(true);
Query q = qp.parse("field:*");

doesn't work at all.

Do I have to reopen the DirectoryReader after each commit?

As we could see the main difference between two snippies is the time u got a reader from the IndexWriter , first one is after the writer.commit() .


when we got a reader ,that means we've got a one-time-snapshot of the current Index file, the second reader got a "snapshot" before the IndexWriter.commit , it will turn out that the IndexSearcher based on that reader won't find changes IndexWriter just made or the Index isn't in a consistent state .

so u should reopen the DirectoryReader . hope these will do some help ! :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM