在 Web 应用程序中,我为整个应用程序设置了一个 IndexReader
和一个相应的 IndexSearcher
。
文档说它们是线程安全的,所以没关系,但是如果底层索引发生变化(例如 IndexWriter
进行更改)它是否应该正常工作?
最佳答案
是的,您需要重新打开阅读器。
使用 SearcherManager自动更新阅读器,调用 maybeRefresh当您做出更改时。
以下 Scala 代码示例:
@volatile protected var LAST_SEARCHER_REFRESH = 0
protected lazy val SEARCHER_MANAGER = new SearcherManager (LUCENE_DIR, new SearcherFactory {
override def newSearcher (reader: IndexReader): IndexSearcher = {new IndexSearcher (reader)}
})
...
if (LAST_SEARCHER_REFRESH != Time.relativeSeconds()) {LAST_SEARCHER_REFRESH = Time.relativeSeconds(); SEARCHER_MANAGER.maybeRefresh()}
val searcher = SEARCHER_MANAGER.acquire(); try {
searcher.search (query, collector)
...
} finally {SEARCHER_MANAGER.release (searcher)}
但有时您必须实现自己的缓存,例如 when you need to synchronize the IndexReader with TaxonomyReader . IndexSearcher description有关于如何做到这一点的建议(有一条通过 DirectoryReader.open(IndexWriter, applyAllDeletes) 的快速路径,可以从用于提交更改的作者那里创建新的读者)。
关于java - 您是否每次都需要一个新的 IndexReader 和 IndexSearcher 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18347100/