8.7.0 版本lucene中,TermsEnum类有如下几个方法
java
/** Returns the number of documents containing the current
term. Do not call this when the enum is unpositioned.
{@link SeekStatus#END}.*/
public abstract int docFreq() throws IOException;
/** Returns the total number of occurrences of this term
across all documents (the sum of the freq() for each
doc that has this term). Note that, like
other term measures, this measure does not take
deleted documents into account. */
public abstract long totalTermFreq() throws IOException;
Terms类有如下几个方法
java
/** Returns the sum of {@link TermsEnum#totalTermFreq} for
all terms in this field. Note that, just like other term
measures, this measure does not take deleted documents
into account. */
public abstract long getSumTotalTermFreq() throws IOException;
/** Returns the sum of {@link TermsEnum#docFreq()} for
all terms in this field. Note that, just like other term
measures, this measure does not take deleted documents
into account. */
public abstract long getSumDocFreq() throws IOException;
/** Returns the number of documents that have at least one
term for this field. Note that, just like other term
measures, this measure does not take deleted documents
into account. */
public abstract int getDocCount() throws IOException;
他们有啥区别?
这几个 Lucene 方法确实有重要区别,让我通过例子来说明:
假设有以下文档集合:
Doc1: "apple apple banana"
Doc2: "apple orange"
Doc3: "banana orange orange"
Doc4: "grape"
各方法的区别:
1. docFreq()
- 单个词项的文档频率
- 含义:当前词项出现在多少个文档中
- 示例 :
- "apple" 的 docFreq = 2(出现在 Doc1, Doc2)
- "orange" 的 docFreq = 2(出现在 Doc2, Doc3)
- "grape" 的 docFreq = 1(仅在 Doc4)
2. totalTermFreq()
- 单个词项的总频率
- 含义:当前词项在所有文档中出现的总次数
- 示例 :
- "apple" 的 totalTermFreq = 3(Doc1中2次 + Doc2中1次)
- "orange" 的 totalTermFreq = 3(Doc2中1次 + Doc3中2次)
- "grape" 的 totalTermFreq = 1
3. getSumTotalTermFreq()
- 字段中所有词项的总频率
- 含义:该字段中所有词项出现次数的总和
- 示例 :整个字段的 sumTotalTermFreq = 8
- apple(3) + banana(2) + orange(3) + grape(1) = 9
4. getSumDocFreq()
- 字段中所有词项的文档频率总和
- 含义:所有词项的 docFreq 之和
- 示例 :sumDocFreq = 7
- apple(2) + banana(2) + orange(2) + grape(1) = 7
5. getDocCount()
- 包含该字段的文档数
- 含义:有多少文档至少包含该字段的一个词项
- 示例:docCount = 4(所有4个文档都有内容)
实际应用场景:
java
// 示例代码
Terms terms = reader.terms("content");
TermsEnum termsEnum = terms.iterator();
// 遍历某个词项
if (termsEnum.seekExact(new BytesRef("apple"))) {
// 针对 "apple" 这个词
int df = termsEnum.docFreq(); // 2 (在2个文档中)
long tf = termsEnum.totalTermFreq(); // 3 (总共出现3次)
}
// 字段级统计
long sumTF = terms.getSumTotalTermFreq(); // 所有词的总频率
long sumDF = terms.getSumDocFreq(); // 所有词的文档频率和
int docCount = terms.getDocCount(); // 包含此字段的文档数
关键区别总结:
方法 | 作用域 | 统计内容 |
---|---|---|
docFreq() |
单个词项 | 文档数量 |
totalTermFreq() |
单个词项 | 出现总次数 |
getSumTotalTermFreq() |
整个字段 | 所有词项的总出现次数 |
getSumDocFreq() |
整个字段 | 所有词项的文档频率之和 |
getDocCount() |
整个字段 | 包含该字段的文档数 |
这些统计信息在计算 TF-IDF、BM25 等相关性评分时非常重要。