如何从 Lucene 8.6.1 索引中获取所有标记的列表?

How to get a list of all tokens from Lucene 8.6.1 index?

我看过how to get a list of all tokens from Solr/Lucene index? but Lucene 8.6.1 doesn't seem to offer IndexReader.terms(). Has it been moved or replaced? Is there an easier way than this answer?

一些历史

您问:我只是想知道 IndexReader.terms() 是否已经移动或被替代品取代。

Lucene v3 方法IndexReader.terms() was moved to AtomicReader in Lucene v4. This was documented in the v4 alpha release notes

(请记住,Lucene v4 早在 2012 年就发布了。)

v4 中 AtomicReader 中的方法采用 field name.

如 v4 发行说明所述:

One big difference is that field and terms are now enumerated separately: a TermsEnum provides a BytesRef (wraps a byte[]) per term within a single field, not a Term.

关键部分 “单个字段中的每个术语”。所以从那时起,不再有一个 API 调用来从索引中检索所有术语。

这种方法已经延续到后来的版本——除了 AtomicReaderAtomicReaderContext 类 在 Lucene v 中被重命名为 LeafReaderLeafReaderContext 5.0.0。参见 Lucene-5569

最新发布

这使我们能够访问术语列表 - 但仅限于每个字段:

以下代码基于最新版本的 Lucene (8.7.0),但也适用于您提到的版本 (8.6.1) - 例如使用 Java:

private void getTokensForField(IndexReader reader, String fieldName) throws IOException {
    List<LeafReaderContext> list = reader.leaves();

    for (LeafReaderContext lrc : list) {
        Terms terms = lrc.reader().terms(fieldName);
        if (terms != null) {
            TermsEnum termsEnum = terms.iterator();

            BytesRef term;
            while ((term = termsEnum.next()) != null) {
                System.out.println(term.utf8ToString());
            }
        }
    }
}

以上示例假设索引如下:

private static final String INDEX_PATH = "/path/to/index/directory";
...
IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(INDEX_PATH)));

如果您需要枚举字段名称, 中的代码可能会提供一个起点。

最后的笔记

我想您也可以在 每个文档 的基础上访问术语,而不是 每个字段 的基础,如评论中所述.这个我没试过。