Как получить список всех токенов из индекса Lucene 8.6.1 с помощью PyLucene?

У меня есть указания от этот вопрос. Сначала я делаю индекс, как показано ниже.

import lucene
from  org.apache.lucene.analysis.standard import StandardAnalyzer
from org.apache.lucene.index import IndexWriterConfig, IndexWriter, DirectoryReader
from org.apache.lucene.store import SimpleFSDirectory
from java.nio.file import Paths
from org.apache.lucene.document import Document, Field, TextField
from org.apache.lucene.util import BytesRefIterator

index_path = "./index"

lucene.initVM()

analyzer = StandardAnalyzer()
config = IndexWriterConfig(analyzer)
if len(os.listdir(index_path))>0:
    config.setOpenMode(IndexWriterConfig.OpenMode.APPEND)

store = SimpleFSDirectory(Paths.get(index_path))
writer = IndexWriter(store, config)

doc = Document()
doc.add(Field("docid", "1",  TextField.TYPE_STORED))
doc.add(Field("title", "qwe rty", TextField.TYPE_STORED))
doc.add(Field("description", "uio pas", TextField.TYPE_STORED))
writer.addDocument(doc)

writer.close()
store.close()

Затем я пытаюсь получить все термины в индексе для одного поля, как показано ниже.

store = SimpleFSDirectory(Paths.get(index_path))
reader = DirectoryReader.open(store)

Попытка 1: попытка использовать next() как в этот вопрос, который, кажется, является методом BytesRefIterator, реализованным TermsEnum.

for lrc in reader.leaves():
    terms = lrc.reader().terms('title')
    terms_enum = terms.iterator()
    while terms_enum.next():
        term = terms_enum.term()
        print(term.utf8ToString())

Однако я не могу получить доступ к этому методу next().

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-47-6515079843a0> in <module>
      2     terms = lrc.reader().terms('title')
      3     terms_enum = terms.iterator()
----> 4     while terms_enum.next():
      5         term = terms_enum.term()
      6         print(term.utf8ToString())

AttributeError: 'TermsEnum' object has no attribute 'next'

Попытка 2: попытка изменить цикл while, как это предлагается в комментариях этот вопрос.

while next(terms_enum):
    term = terms_enum.term()
    print(term.utf8ToString())

Однако, похоже, Python не считает TermsEnum итератором.

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-48-d490ad78fb1c> in <module>
      2     terms = lrc.reader().terms('title')
      3     terms_enum = terms.iterator()
----> 4     while next(terms_enum):
      5         term = terms_enum.term()
      6         print(term.utf8ToString())

TypeError: 'TermsEnum' object is not an iterator

Я знаю, что на мой вопрос можно ответить, как предложено в этот вопрос. Тогда я думаю, что мой вопрос действительно заключается в том, как мне получить все термины в TermsEnum?


person PSK    schedule 22.11.2020    source источник


Ответы (1)


Я обнаружил, что нижеследующее работает с здесь и из test_FieldEnumeration() в файле test_Pylucene.py, который находится в pylucene-8.6.1/test3/.

for term in BytesRefIterator.cast_(terms_enum):
    print(term.utf8ToString())

Рад принять ответ, который имеет больше объяснений, чем этот.

person PSK    schedule 23.11.2020