我需要我在Lucene中的结果在添加文档后立即可用。我读到的所有内容都说我应该缓存IndexSearcher实例,但我不知道如何在每次写入时都重新打开IndexReader以及IndexSearcher的情况下实现我想要的内容……
我做错了什么?
class LuceneStorage {
private final Directory luceneDirectory;
private final IndexWriter indexWriter;
private volatile DirectoryReader indexReader;
LuceneStorage() {
try {
this.luceneDirectory = NIOFSDirectory.open(Paths.get(System.getProperty("user.home")).resolve("lucene"));
IndexWriterConfig config = new IndexWriterConfig(new KeywordAnalyzer());
config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
this.indexWriter = new IndexWriter(luceneDirectory, config);
this.indexReader = DirectoryReader.open(indexWriter);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public Stream<String> read(String id) {
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
QueryParser queryParser = new QueryParser("id", new KeywordAnalyzer());
StreamableSimpleCollector collector = new StreamableSimpleCollector();
try {
indexSearcher.search(queryParser.parse(id), collector);
} catch (Exception e) {
throw new IllegalStateException(e);
}
IntStream docIds = collector.stream();
return docIds.mapToObj(i -> {
try {
return indexSearcher.doc(i).get("content");
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
public String write(String content, String... ids) {
String uuid = UUID.randomUUID().toString();
Document document = new Document();
document.add(new StringField("id", uuid, Field.Store.YES));
Stream.of(ids)
.forEach(i -> document.add(new StringField("id", i, Field.Store.YES)));
document.add(new StoredField("content", content));
try {
indexWriter.addDocument(document);
indexReader = DirectoryReader.openIfChanged(indexReader);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return uuid;
}
}发布于 2016-03-06 23:13:59
Lucene不是为了提供实时搜索结果而设计的。因此,如果这真的是一个要求,你应该考虑其他东西。
然而Lucene可以提供近乎实时的搜索结果,所以你的用户最多只能等待。在更改可搜索之前的1秒。这样做的方法是使用SearcherManager (http://lucene.apache.org/core/5_5_0/core/org/apache/lucene/search/SearcherManager.html),并拥有一个定期刷新当前索引读取器的后台线程。
https://stackoverflow.com/questions/35703665
复制相似问题