1 package org.apache.lucene.search; 2 3 18 19 import java.io.IOException ; 20 import java.util.BitSet ; 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 27 36 public class IndexSearcher extends Searcher { 37 IndexReader reader; 38 private boolean closeReader; 39 40 41 public IndexSearcher(String path) throws IOException { 42 this(IndexReader.open(path), true); 43 } 44 45 46 public IndexSearcher(Directory directory) throws IOException { 47 this(IndexReader.open(directory), true); 48 } 49 50 51 public IndexSearcher(IndexReader r) { 52 this(r, false); 53 } 54 55 private IndexSearcher(IndexReader r, boolean closeReader) { 56 reader = r; 57 this.closeReader = closeReader; 58 } 59 60 61 public IndexReader getIndexReader() { 62 return reader; 63 } 64 65 71 public void close() throws IOException { 72 if(closeReader) 73 reader.close(); 74 } 75 76 public int docFreq(Term term) throws IOException { 78 return reader.docFreq(term); 79 } 80 81 public Document doc(int i) throws IOException { 83 return reader.document(i); 84 } 85 86 public int maxDoc() throws IOException { 88 return reader.maxDoc(); 89 } 90 91 public TopDocs search(Weight weight, Filter filter, final int nDocs) 93 throws IOException { 94 95 if (nDocs <= 0) throw new IllegalArgumentException ("nDocs must be > 0"); 97 98 TopDocCollector collector = new TopDocCollector(nDocs); 99 search(weight, filter, collector); 100 return collector.topDocs(); 101 } 102 103 public TopFieldDocs search(Weight weight, Filter filter, final int nDocs, 105 Sort sort) 106 throws IOException { 107 108 TopFieldDocCollector collector = 109 new TopFieldDocCollector(reader, sort, nDocs); 110 search(weight, filter, collector); 111 return (TopFieldDocs)collector.topDocs(); 112 } 113 114 public void search(Weight weight, Filter filter, 116 final HitCollector results) throws IOException { 117 HitCollector collector = results; 118 if (filter != null) { 119 final BitSet bits = filter.bits(reader); 120 collector = new HitCollector() { 121 public final void collect(int doc, float score) { 122 if (bits.get(doc)) { results.collect(doc, score); 124 } 125 } 126 }; 127 } 128 129 Scorer scorer = weight.scorer(reader); 130 if (scorer == null) 131 return; 132 scorer.score(collector); 133 } 134 135 public Query rewrite(Query original) throws IOException { 136 Query query = original; 137 for (Query rewrittenQuery = query.rewrite(reader); rewrittenQuery != query; 138 rewrittenQuery = query.rewrite(reader)) { 139 query = rewrittenQuery; 140 } 141 return query; 142 } 143 144 public Explanation explain(Weight weight, int doc) throws IOException { 145 return weight.explain(reader, doc); 146 } 147 } 148 | Popular Tags |