1 17 18 19 20 package org.apache.lenya.lucene; 21 22 import java.io.BufferedReader ; 23 import java.io.File ; 24 import java.io.InputStreamReader ; 25 26 import org.apache.lucene.analysis.Analyzer; 27 import org.apache.lucene.analysis.standard.StandardAnalyzer; 28 import org.apache.lucene.document.Document; 29 import org.apache.lucene.queryParser.QueryParser; 30 import org.apache.lucene.search.Hits; 31 import org.apache.lucene.search.IndexSearcher; 32 import org.apache.lucene.search.Query; 33 import org.apache.lucene.search.Searcher; 34 35 38 class SearchFiles { 39 40 45 public static void main(String [] args) { 46 if (args.length == 0) { 47 System.err.println("Usage: org.apache.lenya.lucene.SearchFiles \"directory_where_index_is_located\" <word>"); 48 return; 49 } 50 51 File index_directory = new File (args[0]); 52 53 if (!index_directory.exists()) { 54 System.err.println("Exception: No such directory: " + 55 index_directory.getAbsolutePath()); 56 57 return; 58 } 59 60 61 try { 62 if (args.length > 1) { 63 Hits hits = new SearchFiles().search(args[1], index_directory); 64 return; 65 } 66 67 BufferedReader in = new BufferedReader (new InputStreamReader (System.in)); 68 69 while (true) { 70 System.out.print("Search: "); 71 72 String line = in.readLine(); 73 74 if (line.length() == -1) { 75 break; 76 } 77 78 Hits hits = new SearchFiles().search(line, index_directory); 79 80 System.out.print("\nAnother Search (y/n) ? "); 81 line = in.readLine(); 82 83 if ((line.length() == 0) || (line.charAt(0) == 'n')) { 84 break; 85 } 86 } 87 88 } catch (Exception e) { 89 System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage()); 90 } 91 } 92 93 96 public Hits search(String line, File index_directory) throws Exception { 97 Searcher searcher = new IndexSearcher(index_directory.getAbsolutePath()); 98 Analyzer analyzer = new StandardAnalyzer(); 99 100 Query query = QueryParser.parse(line, "contents", analyzer); 101 System.out.println("Searching for: " + query.toString("contents")); 102 103 Hits hits = searcher.search(query); 104 System.out.println("Total matching documents: " + hits.length()); 105 106 final int HITS_PER_PAGE = 10; 107 108 for (int start = 0; start < hits.length(); start += HITS_PER_PAGE) { 109 int end = Math.min(hits.length(), start + HITS_PER_PAGE); 110 111 for (int i = start; i < end; i++) { 112 Document doc = hits.doc(i); 113 String path = doc.get("path"); 114 115 if (path != null) { 116 System.out.println(i + ". " + path); 117 } else { 118 String url = doc.get("url"); 119 120 if (url != null) { 121 System.out.println(i + ". " + url); 122 System.out.println(" - " + doc.get("title")); 123 } else { 124 System.out.println(i + ". " + "No path nor URL for this document"); 125 } 126 } 127 } 128 129 } 130 searcher.close(); 131 return hits; 132 } 133 } 134 | Popular Tags |