1 26 27 29 package de.nava.informa.search; 30 31 import java.io.IOException ; 32 import java.util.List ; 33 import java.util.ArrayList ; 34 35 import org.apache.lucene.analysis.Analyzer; 36 import org.apache.lucene.analysis.standard.StandardAnalyzer; 37 import org.apache.lucene.document.Document; 38 import org.apache.lucene.queryParser.QueryParser; 39 import org.apache.lucene.queryParser.ParseException; 40 import org.apache.lucene.search.Searcher; 41 import org.apache.lucene.search.IndexSearcher; 42 import org.apache.lucene.search.Query; 43 import org.apache.lucene.search.Hits; 44 import org.apache.commons.logging.Log; 45 import org.apache.commons.logging.LogFactory; 46 47 import de.nava.informa.core.ChannelIF; 48 import de.nava.informa.core.ItemIF; 49 import de.nava.informa.core.ChannelGroupIF; 50 51 57 public class ChannelSearcher { 58 59 private static Log logger = LogFactory.getLog(ChannelSearcher.class); 60 61 65 public static final int DEFAULT_MAX_RESULTS = 25; 66 67 private String indexDir; 68 private Analyzer analyzer; 69 private Searcher searcher; 70 private int nrOfHits; 71 72 80 public ChannelSearcher(String indexDir) throws IOException { 81 this.indexDir = indexDir; 82 this.analyzer = new StandardAnalyzer(); 83 this.searcher = new IndexSearcher(indexDir); 84 this.nrOfHits = 0; 85 } 86 87 95 public List search(ChannelGroupIF channels, String queryString) 96 throws QueryParseException, IOException { 97 return search(channels, queryString, DEFAULT_MAX_RESULTS); 98 } 99 100 107 public List search(ChannelGroupIF channels, 108 String queryString, int maxResults) 109 throws QueryParseException, IOException { 110 111 Query query = null; 112 try { 113 logger.info("Searching for '" + queryString + "'."); 114 query = QueryParser.parse(queryString, 115 ItemFieldConstants.TITLE_AND_DESC, 116 analyzer); 117 } catch (ParseException pe) { 118 throw new QueryParseException(pe); 120 } 121 Hits hits = searcher.search(query); 122 nrOfHits = hits.length(); 123 logger.info("Query returned " + nrOfHits + " hits."); 124 List results = new ArrayList (); 125 for (int i = 0; i < hits.length() && i < maxResults; i++) { 126 Document doc = hits.doc(i); 127 long channelId = Long.parseLong(doc.get(ItemFieldConstants.CHANNEL_ID)); 128 ChannelIF channel = channels.getById(channelId); 129 if (channel == null) { 130 throw new UnretrievableException("channel " + channelId); 131 } 132 long itemId = Long.parseLong(doc.get(ItemFieldConstants.ITEM_ID)); 134 ItemIF item = channel.getItem(itemId); 135 if (item == null) { 136 throw new UnretrievableException("item " + itemId); 137 } 138 results.add(new ItemResult(item, hits.score(i))); 139 } 140 searcher.close(); 141 return results; 142 } 143 144 151 public int getNrOfHits() { 152 return nrOfHits; 153 } 154 155 public void setIndexDir(String indexDir) { 156 this.indexDir = indexDir; 157 } 158 159 public String getIndexDir() { 160 return indexDir; 161 } 162 163 } 164 | Popular Tags |