使用Lucene(PyLucene)查找单个字段的术语

3

我对Lucene的Term Vectors相对陌生,但希望确保我的术语收集尽可能高效。

我正在获取唯一的术语,然后检索术语的docFreq()以执行聚合。

我使用以下方法从索引中收集所有文档的术语:

lindex = SimpleFSDirectory(File(indexdir))
ireader = IndexReader.open(lindex, True)
terms = ireader.terms() #Returns TermEnum

这样做很好,但有没有一种方法只返回特定字段的术语(跨所有文档) - 那不是更有效率吗?
例如:
 ireader.terms(Field="country")

我认为这可能是解决方案... http://wiki.apache.org/lucene-java/LuceneFAQ#How_do_I_retrieve_all_the_values_of_a_particular_field_that_exists_within_an_index.2C_across_all_documents.3F - Ben DeMott
1个回答

3
IndexReader.terms()接受一个可选的Field()对象。Field对象由两个参数组成,即字段名称和值,Lucene将其称为“Term Field”和“Term Text”。
通过提供一个带有空值“term text”的Field参数,我们可以从我们关心的术语开始进行术语迭代。
lindex = SimpleFSDirectory(File(indexdir))
ireader = IndexReader.open(lindex, True)
# Query the lucene index for the terms starting at a term named "field_name"
terms = ireader.terms(Term("field_name", "")) #Start at the field "field_name"
facets = {'other': 0}
while terms.next():
    if terms.term().field() != "field_name":  #We've got every value
        break
    print "Field Name:", terms.term().field()
    print "Field Value:", terms.term().text()
    print "Matching Docs:", int(ireader.docFreq(term))

希望其他寻找如何在PyLucene中执行分面的人能够看到这篇文章。关键是将术语索引为原样。仅为完整起见,以下是应如何索引字段值的方法。
dir = SimpleFSDirectory(File(indexdir))
analyzer = StandardAnalyzer(Version.LUCENE_30)
writer = IndexWriter(dir, analyzer, True, IndexWriter.MaxFieldLength(512))
print "Currently there are %d documents in the index..." % writer.numDocs()
print "Adding %s Documents to Index..." % docs.count()
for val in terms:
    doc = Document()
    #Store the field, as-is, with term-vectors.
    doc.add(Field("field_name", val, Field.Store.YES, Field.Index.NOT_ANALYZED, Field.TermVector.YES))
    writer.addDocument(doc)

writer.optimize()
writer.close()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接