List of usage examples for org.apache.lucene.search IndexSearcher doc
public Document doc(int docID) throws IOException
.getIndexReader().document(docID)
From source file:net.asteasolutions.cinusuidi.sluncho.documentIndex.FullTextSearcher.java
public String searchById(String docId) throws ParseException, IOException { ArrayList<DocumentIndexEntry> result = new ArrayList<DocumentIndexEntry>(); String indexPath = "fullTextIndex"; IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexPath))); IndexSearcher searcher = new IndexSearcher(reader); Analyzer analyzer = new StandardAnalyzer(); QueryParser parser = new QueryParser("questionId", analyzer); String queryString = docId;//w w w.j av a 2 s.com Query query = parser.parse(queryString); TopDocs results = searcher.search(query, 1); ScoreDoc[] hits = results.scoreDocs; int numTotalHits = results.totalHits; if (numTotalHits > 0) { Document doc = searcher.doc(hits[0].doc); DocumentIndexEntry entity = new DocumentIndexEntry(); return doc.get("answer"); } return "Could not find an answer to your question"; }
From source file:net.bobah.mail.Indexer.java
License:Apache License
private void index(File file, IndexWriter writer, IndexSearcher searcher) throws IOException, MessagingException { if (searcher != null) { final Query query = new TermQuery(new Term("id", file.getName())); TopDocs docs = searcher.search(query, 1); if (docs.totalHits == 1) { int docID = docs.scoreDocs[0].doc; Document indexedDoc = searcher.doc(docID); final long indexedStamp = indexedDoc.getField("stamp").numericValue().longValue(); if (indexedStamp >= file.lastModified()) { log.debug("{} - unchanged", file.getName()); return; } else { log.debug("{} - reindexing", file.getName()); writer.deleteDocuments(query); }//from w ww. j a v a2s. c o m } else { log.info("{} - indexing", file.getName()); } } else { log.info("{} - indexing", file.getName()); } final MimeMessage msg = readMessage(file, log); final Document doc = new Document(); doc.add(new StringField("id", file.getName(), Store.YES)); doc.add(new LongField("stamp", file.lastModified(), Store.YES)); doc.add(new StringField("path", file.getAbsolutePath(), Store.YES)); final Enumeration<?> headers = msg.getAllHeaders(); while (headers.hasMoreElements()) { Header header = (Header) headers.nextElement(); doc.add(new TextField(header.getName(), header.getValue(), Store.YES)); } if (msg.getContentType() != null) { final String contentType = msg.getContentType().toLowerCase(); if (contentType.startsWith("multipart/")) { final Multipart multiPart = (Multipart) msg.getContent(); for (int i = 0; i < multiPart.getCount(); ++i) { final BodyPart bodyPart = multiPart.getBodyPart(i); doc.add(new TextField(String.format("body-%d", i), extractText(bodyPart.getContentType().toLowerCase(), bodyPart.getContent()), Store.NO)); } } else { doc.add(new TextField("body", extractText(contentType, msg.getContent()), Store.NO)); } writer.addDocument(doc); } //file.setLastModified(mime.getSentDate().getTime()); }
From source file:net.chwise.websearch.SearchServlet.java
License:Open Source License
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String queryText = req.getParameter("q"); if (queryText == null) queryText = ""; String[] smilesQueriesString = req.getParameterValues("sq"); //Join text query with structures query StringBuffer sb = new StringBuffer(); boolean nonEmptyQuery = isQuery(queryText); if (nonEmptyQuery) sb.append(queryText);//w w w.jav a 2 s .co m if (smilesQueriesString != null) { for (String structSmiles : smilesQueriesString) { if (!isQuery(structSmiles)) continue; String escapedSmiles = QueryParser.escape(structSmiles); if (nonEmptyQuery) { sb.append(" AND "); } sb.append(" smiles:"); sb.append(escapedSmiles); nonEmptyQuery = true; } } String joinedTextChemicalQuery = sb.toString(); LOGGER.log(Level.INFO, "Query: {0}", joinedTextChemicalQuery); int from = 0; int numShow = 10; String strFrom = req.getParameter("from"); String strNumShow = req.getParameter("numShow"); if (strFrom != null) from = Integer.parseInt(strFrom); if (strNumShow != null) numShow = Math.min(Integer.parseInt(strNumShow), 20); int to = from + numShow; Integer[] fromTo = { new Integer(from), new Integer(to) }; LOGGER.log(Level.INFO, "Requested results range: from {0} to {1}", fromTo); JSONObject jsonResponse = new JSONObject(); JSONArray jsonResult = new JSONArray(); try { //Preapre for search String directorySourceClassName = getServletConfig().getInitParameter("directorySourceClassName"); String directorySourceParams = getServletConfig().getInitParameter("directorySourceParams"); Directory directory = directorySource.getDirectory(directorySourceClassName, directorySourceParams); IndexReader reader = null; reader = IndexReader.open(directory); IndexSearcher searcher = new IndexSearcher(reader); //Perform query Query query = null; Analyzer analyzer = getAnalyzer(); query = new MultiFieldQueryParser(Version.LUCENE_43, getTextFields(), analyzer, getFieldWeights()) .parse(joinedTextChemicalQuery); TopScoreDocCollector collector = TopScoreDocCollector.create(to, true); //TODO: use from, to searcher.search(query, collector); ScoreDoc[] hits = collector.topDocs().scoreDocs; int totalResults = collector.getTotalHits(); LOGGER.log(Level.INFO, "Found {0} documents", hits.length); //Wrap results into json object HighlightedFragmentsRetriever highlighter = new HighlightedFragmentsRetriever(); to = Math.min(to, hits.length); for (int i = from; i < to; ++i) { ScoreDoc hit = hits[i]; Document foundDoc = searcher.doc(hit.doc); JSONObject jsonDoc = extractJSON(query, analyzer, highlighter, foundDoc); jsonResult.put(jsonDoc); } jsonResponse.put("result", jsonResult); jsonResponse.put("total", totalResults); } catch (ParseException e) { JSONObject jsonFailure = SearchFailureJSONResponse.create("info", "We couldn't understand query", "Use quotes for phrase search. Use AND,OR,NOT for boolean search"); try { jsonResponse.put("failure", jsonFailure); } catch (JSONException e1) { e1.printStackTrace(); throw new RuntimeException(e1); } } catch (RuntimeException e) { if (e.getCause() instanceof InvalidSmilesException) { JSONObject jsonFailure = SearchFailureJSONResponse.create("info", "We couldn't understand query", "Your structure formula doesn't seem like correct SMILES. Use structure editor for generating correct SMILES structures"); try { jsonResponse.put("failure", jsonFailure); } catch (JSONException e1) { e1.printStackTrace(); throw new RuntimeException(e1); } } else { e.printStackTrace(); throw e; } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception in servlet SearchServlet", e); } resp.setContentType("application/json"); PrintWriter out = resp.getWriter(); out.print(jsonResponse); out.flush(); }