1 package org.apache.lucene.search; 2 3 18 19 import junit.framework.TestCase; 20 21 import java.util.Collection ; 22 23 import org.apache.lucene.index.Term; 24 import org.apache.lucene.index.IndexWriter; 25 import org.apache.lucene.search.IndexSearcher; 26 import org.apache.lucene.store.RAMDirectory; 27 import org.apache.lucene.analysis.SimpleAnalyzer; 28 import org.apache.lucene.document.Document; 29 import org.apache.lucene.document.Field; 30 31 36 public class TestSimilarity extends TestCase { 37 public TestSimilarity(String name) { 38 super(name); 39 } 40 41 public static class SimpleSimilarity extends Similarity { 42 public float lengthNorm(String field, int numTerms) { return 1.0f; } 43 public float queryNorm(float sumOfSquaredWeights) { return 1.0f; } 44 public float tf(float freq) { return freq; } 45 public float sloppyFreq(int distance) { return 2.0f; } 46 public float idf(Collection terms, Searcher searcher) { return 1.0f; } 47 public float idf(int docFreq, int numDocs) { return 1.0f; } 48 public float coord(int overlap, int maxOverlap) { return 1.0f; } 49 } 50 51 public void testSimilarity() throws Exception { 52 RAMDirectory store = new RAMDirectory(); 53 IndexWriter writer = new IndexWriter(store, new SimpleAnalyzer(), true); 54 writer.setSimilarity(new SimpleSimilarity()); 55 56 Document d1 = new Document(); 57 d1.add(Field.Text("field", "a c")); 58 59 Document d2 = new Document(); 60 d2.add(Field.Text("field", "a b c")); 61 62 writer.addDocument(d1); 63 writer.addDocument(d2); 64 writer.optimize(); 65 writer.close(); 66 67 final float[] scores = new float[4]; 68 69 Searcher searcher = new IndexSearcher(store); 70 searcher.setSimilarity(new SimpleSimilarity()); 71 72 Term a = new Term("field", "a"); 73 Term b = new Term("field", "b"); 74 Term c = new Term("field", "c"); 75 76 searcher.search 77 (new TermQuery(b), 78 new HitCollector() { 79 public final void collect(int doc, float score) { 80 assertTrue(score == 1.0f); 81 } 82 }); 83 84 BooleanQuery bq = new BooleanQuery(); 85 bq.add(new TermQuery(a), false, false); 86 bq.add(new TermQuery(b), false, false); 87 searcher.search 89 (bq, 90 new HitCollector() { 91 public final void collect(int doc, float score) { 92 assertTrue(score == (float)doc+1); 94 } 95 }); 96 97 PhraseQuery pq = new PhraseQuery(); 98 pq.add(a); 99 pq.add(c); 100 searcher.search 102 (pq, 103 new HitCollector() { 104 public final void collect(int doc, float score) { 105 assertTrue(score == 1.0f); 107 } 108 }); 109 110 pq.setSlop(2); 111 searcher.search 113 (pq, 114 new HitCollector() { 115 public final void collect(int doc, float score) { 116 assertTrue(score == 2.0f); 118 } 119 }); 120 } 121 } 122 | Popular Tags |