Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a Lucene / Lucene.net search, how do I count the number of hits per document?

When searching a bunch of documents, I can easily find the number of documents which match my search criteria:

Hits hits = Searcher.Search(query);
int DocumentCount = hits.Length();

How do I determine the total number of hits within the documents? For example, let's say I search for "congress" and I get 2 documents back. How can I get the number of times "congress" occurs in each document? For example let's say "congress" occurs 2 times in document #1 and 3 times in document #2. The result I'm looking for is 5.

like image 362
Keltex Avatar asked Feb 12 '10 02:02

Keltex


1 Answers

This is Lucene Java, but should work for Lucene.NET:

List docIds = // doc ids for documents that matched the query, 
              // sorted in ascending order 

int totalFreq = 0;
TermDocs termDocs = reader.termDocs();
termDocs.seek(new Term("my_field", "congress"));
for (int id : docIds) {
    termDocs.skipTo(id);
    totalFreq += termDocs.freq();
}
like image 125
bajafresh4life Avatar answered Oct 23 '22 03:10

bajafresh4life