1 package org.apache.lucene; 2 3 18 19 import java.util.GregorianCalendar ; 20 import java.io.PrintWriter ; 21 import java.io.StringWriter ; 22 23 import junit.framework.TestCase; 24 import junit.framework.TestSuite; 25 import junit.textui.TestRunner; 26 27 import org.apache.lucene.store.*; 28 import org.apache.lucene.document.*; 29 import org.apache.lucene.analysis.*; 30 import org.apache.lucene.index.*; 31 import org.apache.lucene.search.*; 32 import org.apache.lucene.queryParser.*; 33 34 38 public class TestSearch extends TestCase { 39 40 41 public static void main(String args[]) { 42 TestRunner.run (new TestSuite(TestSearch.class)); 43 } 44 45 54 public void testSearch() throws Exception { 55 StringWriter sw = new StringWriter (); 56 PrintWriter pw = new PrintWriter (sw, true); 57 doTestSearch(pw, false); 58 pw.close(); 59 sw.close(); 60 String multiFileOutput = sw.getBuffer().toString(); 61 63 sw = new StringWriter (); 64 pw = new PrintWriter (sw, true); 65 doTestSearch(pw, true); 66 pw.close(); 67 sw.close(); 68 String singleFileOutput = sw.getBuffer().toString(); 69 70 assertEquals(multiFileOutput, singleFileOutput); 71 } 72 73 74 private void doTestSearch(PrintWriter out, boolean useCompoundFile) 75 throws Exception 76 { 77 Directory directory = new RAMDirectory(); 78 Analyzer analyzer = new SimpleAnalyzer(); 79 IndexWriter writer = new IndexWriter(directory, analyzer, true); 80 81 writer.setUseCompoundFile(useCompoundFile); 82 83 String [] docs = { 84 "a b c d e", 85 "a b c d e a b c d e", 86 "a b c d e f g h i j", 87 "a c e", 88 "e c a", 89 "a c e a c e", 90 "a c e a b c" 91 }; 92 for (int j = 0; j < docs.length; j++) { 93 Document d = new Document(); 94 d.add(Field.Text("contents", docs[j])); 95 writer.addDocument(d); 96 } 97 writer.close(); 98 99 Searcher searcher = new IndexSearcher(directory); 100 101 String [] queries = { 102 "a b", 103 "\"a b\"", 104 "\"a b c\"", 105 "a c", 106 "\"a c\"", 107 "\"a c e\"", 108 }; 109 Hits hits = null; 110 111 QueryParser parser = new QueryParser("contents", analyzer); 112 parser.setPhraseSlop(4); 113 for (int j = 0; j < queries.length; j++) { 114 Query query = parser.parse(queries[j]); 115 out.println("Query: " + query.toString("contents")); 116 117 122 hits = searcher.search(query); 123 124 out.println(hits.length() + " total results"); 125 for (int i = 0 ; i < hits.length() && i < 10; i++) { 126 Document d = hits.doc(i); 127 out.println(i + " " + hits.score(i) 128 + " " + d.get("contents")); 130 } 131 } 132 searcher.close(); 133 } 134 135 static long Time(int year, int month, int day) { 136 GregorianCalendar calendar = new GregorianCalendar (); 137 calendar.set(year, month, day); 138 return calendar.getTime().getTime(); 139 } 140 } 141 | Popular Tags |