我正在尝试将应用程序中的 Lucene 从版本 3.5.0 升级到 5.0.0。该应用程序具有以下代码:
IndexReader indexReader=IndexReader.open(index);
String[] fields = indexReader.getFieldNames(FieldOption.ALL).toArray(new String[0]);
我需要字段名称,因此我在 MultiFieldQueryParser 中使用它们。如何更改至 5.0.0 版本?
最佳答案
您可以使用 LeafReader.getFieldInfos()
从阅读器获取字段信息方法,然后可以从 FieldInfo.name
中获取字段名称:
public static String[] getFieldNames(IndexReader reader) {
List<String> fieldNames = new ArrayList<String>();
//For a simple reader over only one index, reader.leaves() should only return one LeafReaderContext
for (LeafReaderContext readerCtx : reader.leaves()) {
FieldInfos fields = readerCtx.reader().getFieldInfos();
for (FieldInfo field : fields) {
//Check whether the field is indexed and searchable, perhaps?
fieldNames.add(field.name);
}
}
return fieldNames.toArray(new String[fieldNames.size()]);
}
注意:可能值得考虑使用包含您要搜索的所有内容的包罗万象的字段。这是一种常见且非常有用的模式(例如,Elasticsearch 默认情况下执行此操作,其 _all field )
按照这条路线,您可以预期索引会变得更大一些,但这使得它更易于使用,并且性能应该得到提高。
关于java - Lucene IndexReader 升级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35137344/