FileDocCategorySizeDatePackage
TestSimilarity.javaAPI DocApache Lucene 1.93859Mon Feb 20 09:19:32 GMT 2006org.apache.lucene.search

TestSimilarity

public class TestSimilarity extends TestCase
Similarity unit test.
author
Doug Cutting
version
$Revision: 150497 $

Fields Summary
Constructors Summary
public TestSimilarity(String name)

    super(name);
  
Methods Summary
public voidtestSimilarity()

    RAMDirectory store = new RAMDirectory();
    IndexWriter writer = new IndexWriter(store, new SimpleAnalyzer(), true);
    writer.setSimilarity(new SimpleSimilarity());
    
    Document d1 = new Document();
    d1.add(new Field("field", "a c", Field.Store.YES, Field.Index.TOKENIZED));

    Document d2 = new Document();
    d2.add(new Field("field", "a b c", Field.Store.YES, Field.Index.TOKENIZED));
    
    writer.addDocument(d1);
    writer.addDocument(d2);
    writer.optimize();
    writer.close();

    Searcher searcher = new IndexSearcher(store);
    searcher.setSimilarity(new SimpleSimilarity());

    Term a = new Term("field", "a");
    Term b = new Term("field", "b");
    Term c = new Term("field", "c");

    searcher.search
      (new TermQuery(b),
       new HitCollector() {
         public final void collect(int doc, float score) {
           assertTrue(score == 1.0f);
         }
       });

    BooleanQuery bq = new BooleanQuery();
    bq.add(new TermQuery(a), BooleanClause.Occur.SHOULD);
    bq.add(new TermQuery(b), BooleanClause.Occur.SHOULD);
    //System.out.println(bq.toString("field"));
    searcher.search
      (bq,
       new HitCollector() {
         public final void collect(int doc, float score) {
           //System.out.println("Doc=" + doc + " score=" + score);
           assertTrue(score == (float)doc+1);
         }
       });

    PhraseQuery pq = new PhraseQuery();
    pq.add(a);
    pq.add(c);
    //System.out.println(pq.toString("field"));
    searcher.search
      (pq,
       new HitCollector() {
         public final void collect(int doc, float score) {
           //System.out.println("Doc=" + doc + " score=" + score);
           assertTrue(score == 1.0f);
         }
       });

    pq.setSlop(2);
    //System.out.println(pq.toString("field"));
    searcher.search
      (pq,
       new HitCollector() {
         public final void collect(int doc, float score) {
           //System.out.println("Doc=" + doc + " score=" + score);
           assertTrue(score == 2.0f);
         }
       });