Tia Chandrawati
Tia Chandrawati

Reputation: 63

How to get term frequency within each document in Lucene 4.2

Initially I was using Lucene 3.2 to get term and term frequency with code like this:

for(int docNum=0; docNum < ir.numDocs(); docNum++) {
TermFreqVector tfv = ir.getTermFreqVector(docNum, "TERJEMAHAN");
if (tfv == null) {
    // ignore empty fields
    continue;
}
String terms[] = tfv.getTerms();
int termCount = terms.length;
int freqs[] = tfv.getTermFrequencies();

for(int t=0; t < termCount; t++) {
    int freqn = ir.docFreq(new Term("TERJEMAHAN", terms[t])); 
    }
}

How to get term frequency of each document in Lucene 4.2?

Upvotes: 2

Views: 3181

Answers (1)

Alex
Alex

Reputation: 400

I managed to compute a term's frequency using these lines:

Term term = ...;
IndexReader reader = ...;

DocsEnum docEnum = MultiFields.getTermDocsEnum(reader, MultiFields.getLiveDocs(reader), "contents", term.bytes());
int termFreq = 0;

int doc = DocsEnum.NO_MORE_DOCS;
while ((doc = docEnum.nextDoc()) != DocsEnum.NO_MORE_DOCS) {
    termFreq += docEnum.freq();
}

Upvotes: 3

Related Questions