1 16 package org.javabb.lucene.search; 17 18 import java.io.IOException ; 19 import java.util.ArrayList ; 20 import java.util.List ; 21 22 import org.apache.lucene.analysis.Analyzer; 23 import org.apache.lucene.document.Document; 24 import org.apache.lucene.queryParser.MultiFieldQueryParser; 25 import org.apache.lucene.queryParser.ParseException; 26 import org.apache.lucene.search.Hits; 27 import org.apache.lucene.search.IndexSearcher; 28 import org.apache.lucene.search.Query; 29 import org.apache.lucene.store.Directory; 30 import org.apache.lucene.store.FSDirectory; 31 32 import org.javabb.infra.Monitor; 33 import org.javabb.lucene.index.LuceneIndexerException; 34 35 import org.springframework.core.io.Resource; 36 37 38 43 public class SimpleLuceneSearcher implements LuceneSearcher { 44 45 private Directory path; 46 private Analyzer analyzer; 47 48 private static Object monitor = Monitor.MONITOR; 49 50 54 public SimpleLuceneSearcher ( Directory path, Analyzer analyzer ) { 55 56 this.path = path; 57 this.analyzer = analyzer; 58 } 59 60 65 public SimpleLuceneSearcher ( Resource path, Analyzer analyzer ) throws IOException { 66 67 this(FSDirectory.getDirectory(path.getFile(), false), analyzer); 68 } 69 70 73 public List search(String query, String [] fields) { 74 75 List result = new ArrayList (); 76 77 try { 78 79 synchronized (monitor) { 80 81 IndexSearcher searcher = new IndexSearcher(path); 82 83 Query queryObj; 84 queryObj = MultiFieldQueryParser.parse(query, fields, analyzer); 85 86 Hits hits = searcher.search(queryObj); 87 88 for (int i = 0; i < hits.length(); i++) { 89 90 Document document = hits.doc(i); 91 92 String idValue = document.getField("postId").stringValue(); 93 long postId = Long.parseLong(idValue); 94 95 result.add(new Long (postId)); 96 97 } 98 99 searcher.close(); 100 101 } 102 103 } catch (IOException e) { 104 105 String msg = "Can't read the index at path [" + path 106 + "]. It is really exists?"; 107 throw new LuceneIndexerException(msg, e); 108 109 } catch (ParseException e) { 110 111 String msg = "Query syntax is not ok. The query is [" + query + "]"; 112 throw new LuceneIndexerException(msg, e); 113 114 } 115 116 return result; 117 118 } 119 120 } 121 | Popular Tags |