1 package org.apache.lucene.demo; 2 3 18 19 import java.io.IOException ; 20 import java.io.BufferedReader ; 21 import java.io.InputStreamReader ; 22 23 import org.apache.lucene.analysis.Analyzer; 24 import org.apache.lucene.analysis.standard.StandardAnalyzer; 25 import org.apache.lucene.document.Document; 26 import org.apache.lucene.search.Searcher; 27 import org.apache.lucene.search.IndexSearcher; 28 import org.apache.lucene.search.Query; 29 import org.apache.lucene.search.Hits; 30 import org.apache.lucene.queryParser.QueryParser; 31 32 class SearchFiles { 33 public static void main(String [] args) { 34 try { 35 Searcher searcher = new IndexSearcher("index"); 36 Analyzer analyzer = new StandardAnalyzer(); 37 38 BufferedReader in = new BufferedReader (new InputStreamReader (System.in)); 39 while (true) { 40 System.out.print("Query: "); 41 String line = in.readLine(); 42 43 if (line.length() == -1) 44 break; 45 46 Query query = QueryParser.parse(line, "contents", analyzer); 47 System.out.println("Searching for: " + query.toString("contents")); 48 49 Hits hits = searcher.search(query); 50 System.out.println(hits.length() + " total matching documents"); 51 52 final int HITS_PER_PAGE = 10; 53 for (int start = 0; start < hits.length(); start += HITS_PER_PAGE) { 54 int end = Math.min(hits.length(), start + HITS_PER_PAGE); 55 for (int i = start; i < end; i++) { 56 Document doc = hits.doc(i); 57 String path = doc.get("path"); 58 if (path != null) { 59 System.out.println(i + ". " + path); 60 } else { 61 String url = doc.get("url"); 62 if (url != null) { 63 System.out.println(i + ". " + url); 64 System.out.println(" - " + doc.get("title")); 65 } else { 66 System.out.println(i + ". " + "No path nor URL for this document"); 67 } 68 } 69 } 70 71 if (hits.length() > end) { 72 System.out.print("more (y/n) ? "); 73 line = in.readLine(); 74 if (line.length() == 0 || line.charAt(0) == 'n') 75 break; 76 } 77 } 78 } 79 searcher.close(); 80 81 } catch (Exception e) { 82 System.out.println(" caught a " + e.getClass() + 83 "\n with message: " + e.getMessage()); 84 } 85 } 86 } 87 | Popular Tags |