Lucene number of occurrences

I am using Lucene.net in my Web App. Everithing works fine, but now i have to show the number of occurrences of my 'searchstring' in every single document of the hits array. How can i do this? I use usual BooleanQuery.

That is my search:

BooleanQuery bq = new BooleanQuery();
bq.Add(QueryParser.Parse(Lquery, "", CurIndexDescritor.GetLangAnalizer()), false,false);
            BooleanQuery.SetMaxClauseCount(int.MaxValue);

IndexSearcher searcher = new IndexSearcher(indexPath);
            Hits hits = (filter != null) ? searcher.Search(bq, filter) :         searcher.Search(bq);

 for (int i = 0; i < hits.Length(); i++)
        {
            Document doc = hits.Doc(i);
            SearchResultItem MyDb = new SearchResultItem();
            MyDb.key = doc.Get(KeyField);
            MyDb.score = hits.Score(i);
            result.Add(MyDb);
        }

Where can i get the number of occurrences?

Thanks!

Upvotes: 0

Views: 618

Answers (1)

Jf Beaulac
Jf Beaulac

Reputation: 5246

If you dont want the score back and dont want to order the results using score you could probably build a custom Similarity implementation.

I quickly tested the following code, and it appears to work fine with TermQueries and PhraseQueries, i didnt test more query types tho. A PhraseQuery hit counts as a single occurence.

public class OccurenceSimilarity : DefaultSimilarity
{
    public override float Tf(float freq)
    {
        return freq;
    }
    public override float Idf(int docFreq, int numDocs)
    {
        return 1;
    }
    public override float Coord(int overlap, int maxOverlap)
    {
        return 1;
    }
    public override float QueryNorm(float sumOfSquaredWeights)
    {
        return 1;
    }
    public override Explanation.IDFExplanation idfExplain(System.Collections.ICollection terms, Searcher searcher)
    {
        return CACHED_IDF_EXPLAIN;
    }
    public override Explanation.IDFExplanation IdfExplain(Term term, Searcher searcher)
    {
        return CACHED_IDF_EXPLAIN;
    }
    public override float SloppyFreq(int distance)
    {
        return 1;
    }
    private static Explanation.IDFExplanation CACHED_IDF_EXPLAIN = new ExplainIt();
    private class ExplainIt : Explanation.IDFExplanation
    {

        public override string Explain()
        {
            return "1";
        }

        public override float GetIdf()
        {
            return 1.0f;
        }
    }
}

To use it:

Similarity.SetDefault(new OccurenceSimilarity());

Upvotes: 2

Related Questions