본문 바로가기

Lucene

[lucene] Collector sample..


public class TestSearch extends TestCase {

 public void test() throws Exception {

   InstantiatedIndex index = new InstantiatedIndex();
   InstantiatedIndexReader reader = new InstantiatedIndexReader(index);
   IndexSearcher searcher = new IndexSearcher(reader);
   InstantiatedIndexWriter writer = new InstantiatedIndexWriter(index);

   Document doc;
   Collector collector;

   doc = new Document();
   doc.add(new Field("f", "a", Field.Store.NO, Field.Index.NOT_ANALYZED));
   writer.addDocument(doc);
   writer.commit();

   collector = new Collector();
   searcher.search(new TermQuery(new Term("f", "a")), collector);
   assertEquals(1, collector.hits);

   doc = new Document();
   doc.add(new Field("f", "a", Field.Store.NO, Field.Index.NOT_ANALYZED));
   writer.addDocument(doc);
   writer.commit();

   collector = new Collector();
   searcher.search(new TermQuery(new Term("f", "a")), collector);
   assertEquals(2, collector.hits);

 }

 public static class Collector extends HitCollector {
   private int hits = 0;
   public void collect(int doc, float score) {
     hits++;
}
}

by karl wettin


public class AllDocCollector extends HitCollector {
 List<ScoreDoc> docs = new ArrayList<ScoreDoc>();
 public void collect(int doc, float score) {
   if (score > 0.0f) {
     docs.add(new ScoreDoc(doc, score));
   }
 }

 public void reset() {
   docs.clear();
 }

 public List<ScoreDoc> getHits() {
   return docs;
 }
}

by Michael McCandless