01: package org.apache.lucene.search;
02:
03: /**
04: * Licensed to the Apache Software Foundation (ASF) under one or more
05: * contributor license agreements. See the NOTICE file distributed with
06: * this work for additional information regarding copyright ownership.
07: * The ASF licenses this file to You under the Apache License, Version 2.0
08: * (the "License"); you may not use this file except in compliance with
09: * the License. You may obtain a copy of the License at
10: *
11: * http://www.apache.org/licenses/LICENSE-2.0
12: *
13: * Unless required by applicable law or agreed to in writing, software
14: * distributed under the License is distributed on an "AS IS" BASIS,
15: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16: * See the License for the specific language governing permissions and
17: * limitations under the License.
18: */
19:
20: import java.io.IOException;
21:
22: import org.apache.lucene.index.IndexReader;
23:
24: /** A {@link HitCollector} implementation that collects the top-sorting
25: * documents, returning them as a {@link TopFieldDocs}. This is used by {@link
26: * IndexSearcher} to implement {@link TopFieldDocs}-based search.
27: *
28: * <p>This may be extended, overriding the collect method to, e.g.,
29: * conditionally invoke <code>super()</code> in order to filter which
30: * documents are collected.
31: **/
32: public class TopFieldDocCollector extends TopDocCollector {
33:
34: private FieldDoc reusableFD;
35:
36: /** Construct to collect a given number of hits.
37: * @param reader the index to be searched
38: * @param sort the sort criteria
39: * @param numHits the maximum number of hits to collect
40: */
41: public TopFieldDocCollector(IndexReader reader, Sort sort,
42: int numHits) throws IOException {
43: super (numHits, new FieldSortedHitQueue(reader, sort.fields,
44: numHits));
45: }
46:
47: // javadoc inherited
48: public void collect(int doc, float score) {
49: if (score > 0.0f) {
50: totalHits++;
51: if (reusableFD == null)
52: reusableFD = new FieldDoc(doc, score);
53: else {
54: // Whereas TopDocCollector can skip this if the
55: // score is not competitive, we cannot because the
56: // comparators in the FieldSortedHitQueue.lessThan
57: // aren't in general congruent with "higher score
58: // wins"
59: reusableFD.score = score;
60: reusableFD.doc = doc;
61: }
62: reusableFD = (FieldDoc) hq.insertWithOverflow(reusableFD);
63: }
64: }
65:
66: // javadoc inherited
67: public TopDocs topDocs() {
68: FieldSortedHitQueue fshq = (FieldSortedHitQueue) hq;
69: ScoreDoc[] scoreDocs = new ScoreDoc[fshq.size()];
70: for (int i = fshq.size() - 1; i >= 0; i--)
71: // put docs in array
72: scoreDocs[i] = fshq.fillFields((FieldDoc) fshq.pop());
73:
74: return new TopFieldDocs(totalHits, scoreDocs, fshq.getFields(),
75: fshq.getMaxScore());
76: }
77: }
|