1 package org.apache.lucene.search; 2 3 18 19 import org.apache.lucene.search.IndexSearcher; 20 import org.apache.lucene.index.Term; 21 import org.apache.lucene.index.TermEnum; 22 import org.apache.lucene.index.IndexReader; 23 import org.apache.lucene.index.IndexWriter; 24 import org.apache.lucene.store.RAMDirectory; 25 import org.apache.lucene.analysis.SimpleAnalyzer; 26 import org.apache.lucene.document.Document; 27 import org.apache.lucene.document.Field; 28 29 import junit.framework.TestCase; 30 31 import java.io.IOException ; 32 import java.util.LinkedList ; 33 34 40 public class TestPhrasePrefixQuery 41 extends TestCase 42 { 43 public TestPhrasePrefixQuery(String name) 44 { 45 super(name); 46 } 47 48 51 public void testPhrasePrefix() 52 throws IOException 53 { 54 RAMDirectory indexStore = new RAMDirectory(); 55 IndexWriter writer = new IndexWriter(indexStore, new SimpleAnalyzer(), true); 56 Document doc1 = new Document(); 57 Document doc2 = new Document(); 58 Document doc3 = new Document(); 59 Document doc4 = new Document(); 60 Document doc5 = new Document(); 61 doc1.add(Field.Text("body", "blueberry pie")); 62 doc2.add(Field.Text("body", "blueberry strudel")); 63 doc3.add(Field.Text("body", "blueberry pizza")); 64 doc4.add(Field.Text("body", "blueberry chewing gum")); 65 doc5.add(Field.Text("body", "piccadilly circus")); 66 writer.addDocument(doc1); 67 writer.addDocument(doc2); 68 writer.addDocument(doc3); 69 writer.addDocument(doc4); 70 writer.addDocument(doc5); 71 writer.optimize(); 72 writer.close(); 73 74 IndexSearcher searcher = new IndexSearcher(indexStore); 75 76 PhrasePrefixQuery query1 = new PhrasePrefixQuery(); 77 PhrasePrefixQuery query2 = new PhrasePrefixQuery(); 78 query1.add(new Term("body", "blueberry")); 79 query2.add(new Term("body", "strawberry")); 80 81 LinkedList termsWithPrefix = new LinkedList (); 82 IndexReader ir = IndexReader.open(indexStore); 83 84 String prefix = "pi"; 86 TermEnum te = ir.terms(new Term("body", prefix + "*")); 87 do { 88 if (te.term().text().startsWith(prefix)) 89 { 90 termsWithPrefix.add(te.term()); 91 } 92 } while (te.next()); 93 94 query1.add((Term[])termsWithPrefix.toArray(new Term[0])); 95 query2.add((Term[])termsWithPrefix.toArray(new Term[0])); 96 97 Hits result; 98 result = searcher.search(query1); 99 assertEquals(2, result.length()); 100 101 result = searcher.search(query2); 102 assertEquals(0, result.length()); 103 } 104 } 105 | Popular Tags |