remy
remy

Reputation: 1305

Lucene: how to get the score of a document

I want to output the score of documents. The code I write for this is that:

IndexReader reader = IndexReader.open(FSDirectory.open(indexDir));
IndexSearcher searcher = new IndexSearcher(reader);
Analyzer analyzer = new IKAnalyzer();
QueryParser parser = new QueryParser(Version.LUCENE_31, "title",
            analyzer);
Query q = null;
q = parser.parse("MacOS");
TopDocs docs = searcher.search(q, 10);
ScoreDoc[] hits = docs.scoreDocs;
for(int i=0;i<hits.length;++i){
  System.out.println(hits[i].score);
}

but the output is NaN. I want to know how to get the score of the document.

Upvotes: 7

Views: 11056

Answers (3)

Daulet
Daulet

Reputation: 126

        IndexReader reader = IndexReader.open(FSDirectory.open(indexDir));
        IndexSearcher searcher = new IndexSearcher(reader);
        Analyzer analyzer = new IKAnalyzer();
        QueryParser parser = new QueryParser(Version.LUCENE_31, "title", analyzer);
        Query q = null;
        q = parser.parse("MacOS");
        TopDocs docs = searcher.search(q, 10);
        ScoreDoc[] filterScoreDosArray = docs.topDocs().scoreDocs;
        for (int i = 0; i < filterScoreDosArray.length; ++i) {
            int docId = filterScoreDosArray[i].doc;
            Document d = is.doc(docId);
            System.out.println((i + 1) + ". " + d.get("docno")+" Score: "+ filterScoreDosArray[i].score);
        }

try this.

Upvotes: 6

jet
jet

Reputation: 123

additional to daulets answere you have to enable the scoring in the indexSearcher:

...
searcher.setDefaultFieldSortScoring(true, true);
...

I think thats what you meant remy, but that way it should be clearer :)

Upvotes: 12

remy
remy

Reputation: 1305

To print score I should set defaultFieldSortScoring(true,true)

Upvotes: 0

Related Questions