如何识别文件夹中是否存在Lucene.Net索引?
-
05-07-2019 - |
题
我使用Lucene.Net进行索引和搜索文档,我使用以下代码创建或打开索引(如果存在):
IndexWriter writer = new IndexWriter(@"C:\index", new StandardAnalyzer(), !IndexExists);
...
private bool IndexExists
{
get
{
return ??
}
}
现在,如何以简单的方式实现IndexExists
?我不需要抛出任何例外。
解决方案
静态方法IndexReader.IndexExists(字符串路径)(或其重载之一)似乎非常合适。
其他提示
在<!> lt; 4.0是IndexReader.indexExists(org.apache.lucene.store.Directory)
在<!> gt; 4.0是DirectoryReader.indexExists(org.apache.lucene.store.Directory)
你可以使用不带布尔参数的构造函数。如果存在一个索引,那将打开现有索引,如果不存在,则创建一个新索引。
Java文档链接(Lucene.Net也是如此):http://lucene.apache.org/java/2_3_1/api/org/apache/lucene/index/IndexWriter.html#IndexWriter(org.apache.lucene.store.Directory, org.apache.lucene.analysis.Analyzer)
我试图找到这个anwser也没有成功,这就是我在我的代码中使用的方式:
私人布尔IndexExists { 得到 { return IndexDirectory.FileExists(<!> quot; segments.gen <!> quot;); } }
我知道这是一个旧条目,但是Sean Carpenter发布的内容完全正确,即使在最新版本的Lucene .NET中也存在这个构造函数。可以在此处找到IndexWriter类的文档: http://lucenenet.apache.org/docs/3.0 0.3 / D2 / D1D / class_lucene_1_1_net_1_1_index_1_1_index_writer.html#af4620c14320934601058e0e9cac9bfab
糟糕!
这是<!>“直接Java <!>”; Lucene,但它可能适用于其他品种。
在Lucene 4.0.0中,DirectoryReader.indexExists()
的API说
如果指定目录中存在索引,则返回true。
但是在Lucene 4.10.2中,true
的API说
如果索引可能存在于指定目录中,则返回true。 请注意,如果存在损坏的索引,或者进程中存在索引 犯
...是的,它在句子中断了。 NB我从源代码直接编译了我的Javadoc,但是在在线API中可以看到相同的未完成的短语。不仅如此,我还看了Lucene 6.0.0 API,它完全一样。
<!> quot;返回<!>“;然而,短语是:
如果索引存在,则为true;否则是假的
...但我目前认为空目录有时会(?)返回IndexReader
(来自我的单元测试)。无论如何,我不相信它。
如果在空目录上创建indexReader.numDocs()
,则会显示其所有方法都将返回而不会抛出异常。你可以去Document
,这将返回0,但这并不能证明那里没有索引,只是没有IndexSearcher
s。当然,这取决于您的要求。
同样,您可以从这样的IndexWriter
创建<=>,并且可以创建<=>。对于空目录,这些都不会有任何明显的问题。
更好的解决方案:
try {
directoryReader = DirectoryReader.open( fsDir );
} catch ( org.apache.lucene.index.IndexNotFoundException e) {
...
}
据我所知,这似乎是可靠的。