KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > lucene > search > TopDocCollector


1 package org.apache.lucene.search;
2
3 /**
4  * Copyright 2004 The Apache Software Foundation
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18
19 import java.io.IOException JavaDoc;
20 import java.util.BitSet JavaDoc;
21
22 import org.apache.lucene.store.Directory;
23 import org.apache.lucene.document.Document;
24 import org.apache.lucene.index.IndexReader;
25 import org.apache.lucene.index.Term;
26 import org.apache.lucene.util.PriorityQueue;
27
28 /** A {@link HitCollector} implementation that collects the top-scoring
29  * documents, returning them as a {@link TopDocs}. This is used by {@link
30  * IndexSearcher} to implement {@link TopDocs}-based search.
31  *
32  * <p>This may be extended, overriding the collect method to, e.g.,
33  * conditionally invoke <code>super()</code> in order to filter which
34  * documents are collected.
35  **/

36 public class TopDocCollector extends HitCollector {
37   private int numHits;
38   private float minScore = 0.0f;
39
40   int totalHits;
41   PriorityQueue hq;
42     
43   /** Construct to collect a given number of hits.
44    * @param numHits the maximum number of hits to collect
45    */

46   public TopDocCollector(int numHits) {
47     this(numHits, new HitQueue(numHits));
48   }
49
50   TopDocCollector(int numHits, PriorityQueue hq) {
51     this.numHits = numHits;
52     this.hq = hq;
53   }
54
55   // javadoc inherited
56
public void collect(int doc, float score) {
57     if (score > 0.0f) {
58       totalHits++;
59       if (hq.size() < numHits || score >= minScore) {
60         hq.insert(new ScoreDoc(doc, score));
61         minScore = ((ScoreDoc)hq.top()).score; // maintain minScore
62
}
63     }
64   }
65
66   /** The total number of documents that matched this query. */
67   public int getTotalHits() { return totalHits; }
68
69   /** The top-scoring hits. */
70   public TopDocs topDocs() {
71     ScoreDoc[] scoreDocs = new ScoreDoc[hq.size()];
72     for (int i = hq.size()-1; i >= 0; i--) // put docs in array
73
scoreDocs[i] = (ScoreDoc)hq.pop();
74       
75     float maxScore = (totalHits==0)
76       ? Float.NEGATIVE_INFINITY
77       : scoreDocs[0].score;
78     
79     return new TopDocs(totalHits, scoreDocs, maxScore);
80   }
81 }
82
Popular Tags