1 package org.apache.lucene; 2 3 18 19 import java.util.GregorianCalendar ; 20 21 import org.apache.lucene.store.*; 22 import org.apache.lucene.document.*; 23 import org.apache.lucene.analysis.*; 24 import org.apache.lucene.index.*; 25 import org.apache.lucene.search.*; 26 import org.apache.lucene.queryParser.*; 27 28 class SearchTest { 29 public static void main(String [] args) { 30 try { 31 Directory directory = new RAMDirectory(); 32 Analyzer analyzer = new SimpleAnalyzer(); 33 IndexWriter writer = new IndexWriter(directory, analyzer, true); 34 35 String [] docs = { 36 "a b c d e", 37 "a b c d e a b c d e", 38 "a b c d e f g h i j", 39 "a c e", 40 "e c a", 41 "a c e a c e", 42 "a c e a b c" 43 }; 44 for (int j = 0; j < docs.length; j++) { 45 Document d = new Document(); 46 d.add(Field.Text("contents", docs[j])); 47 writer.addDocument(d); 48 } 49 writer.close(); 50 51 Searcher searcher = new IndexSearcher(directory); 52 53 String [] queries = { 54 "\"a c e\"", 60 }; 61 Hits hits = null; 62 63 QueryParser parser = new QueryParser("contents", analyzer); 64 parser.setPhraseSlop(4); 65 for (int j = 0; j < queries.length; j++) { 66 Query query = parser.parse(queries[j]); 67 System.out.println("Query: " + query.toString("contents")); 68 69 74 hits = searcher.search(query); 75 76 System.out.println(hits.length() + " total results"); 77 for (int i = 0 ; i < hits.length() && i < 10; i++) { 78 Document d = hits.doc(i); 79 System.out.println(i + " " + hits.score(i) 80 + " " + d.get("contents")); 82 } 83 } 84 searcher.close(); 85 86 } catch (Exception e) { 87 System.out.println(" caught a " + e.getClass() + 88 "\n with message: " + e.getMessage()); 89 } 90 } 91 92 static long Time(int year, int month, int day) { 93 GregorianCalendar calendar = new GregorianCalendar (); 94 calendar.set(year, month, day); 95 return calendar.getTime().getTime(); 96 } 97 } 98 | Popular Tags |