List of usage examples for org.apache.lucene.search IndexSearcher doc
public Document doc(int docID) throws IOException
.getIndexReader().document(docID)
From source file:com.impetus.kundera.index.LucandraIndexer.java
License:Apache License
@SuppressWarnings("deprecation") @Override//from w ww . j a va2 s . c o m public final List<String> search(String luceneQuery, int start, int count) { if (Constants.INVALID == count) { count = 100; } log.debug("Searhcing index with query[" + luceneQuery + "], start:" + start + ", count:" + count); Set<String> entityIds = new HashSet<String>(); org.apache.lucene.index.IndexReader indexReader = null; try { if (client.getType().equals(DBType.CASSANDRA)) { indexReader = new IndexReader(INDEX_NAME, ((CassandraClient) client).getCassandraClient()); } else { indexReader = getDefaultReader(); } } catch (Exception e) { throw new IndexingException(e.getMessage()); } IndexSearcher searcher = new IndexSearcher(indexReader); QueryParser qp = new QueryParser(Version.LUCENE_CURRENT, DEFAULT_SEARCHABLE_FIELD, analyzer); try { Query q = qp.parse(luceneQuery); TopDocs docs = searcher.search(q, count); for (ScoreDoc sc : docs.scoreDocs) { Document doc = searcher.doc(sc.doc); entityIds.add(doc.get(ENTITY_ID_FIELD)); } } catch (ParseException e) { new IndexingException(e.getMessage()); } catch (IOException e) { new IndexingException(e.getMessage()); } log.debug("Result[" + entityIds + "]"); return new ArrayList<String>(entityIds); }
From source file:com.impetus.kundera.index.LuceneIndexer.java
License:Apache License
/** * search the data from lucene for embeddedid * // w w w. ja v a2 s .c om * @param docs * @param indexCol * @param searcher * @param metadata * @param metaModel */ public void prepareEmbeddedId(TopDocs docs, Map<String, Object> indexCol, IndexSearcher searcher, EntityMetadata metadata, MetamodelImpl metaModel) { try { for (ScoreDoc sc : docs.scoreDocs) { Document doc = searcher.doc(sc.doc); Map<String, Object> embeddedIdFields = new HashMap<String, Object>(); EmbeddableType embeddableId = metaModel.embeddable(metadata.getIdAttribute().getBindableJavaType()); Set<Attribute> embeddedAttributes = embeddableId.getAttributes(); prepareEmbeddedIdFields(embeddedAttributes, metaModel, embeddedIdFields, doc, metadata); String entityId = doc.get(IndexingConstants.ENTITY_ID_FIELD); indexCol.put(entityId, embeddedIdFields); } } catch (Exception e) { log.error("Error while parsing Lucene Query {} ", e); throw new LuceneIndexingException(e); } }
From source file:com.impetus.kundera.index.LuceneIndexer.java
License:Apache License
@Override public final Map<String, Object> search(String luceneQuery, int start, int count, boolean fetchRelation, KunderaMetadata kunderaMetadata, EntityMetadata metadata) { boolean isEmbeddedId = false; MetamodelImpl metaModel = null;/*from ww w . ja v a2 s. co m*/ if (kunderaMetadata != null && metadata != null) { metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata() .getMetamodel(metadata.getPersistenceUnit()); isEmbeddedId = metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType()); } reader = getIndexReader(); if (Constants.INVALID == count) { count = 100; } if (log.isDebugEnabled()) { log.debug("Searching index with query[{}], start:{} , count:" + count, luceneQuery, start); } // Set<String> entityIds = new HashSet<String>(); Map<String, Object> indexCol = new HashMap<String, Object>(); if (reader == null) { return indexCol; // throw new // LuceneIndexingException("Index reader is not initialized!"); } QueryParser qp = null; IndexSearcher searcher = new IndexSearcher(reader); qp = new QueryParser(DEFAULT_SEARCHABLE_FIELD, new StandardAnalyzer()); try { // to make like query case insensitive // qp.setLowercaseExpandedTerms(true); qp.setAllowLeadingWildcard(true); // qp.set Query q = qp.parse(luceneQuery); TopDocs docs = searcher.search(q, count); int nullCount = 0; // Assuming Supercol will be null in case if alias only. // This is a quick fix if (isEmbeddedId) { prepareEmbeddedId(docs, indexCol, searcher, metadata, metaModel); } else { for (ScoreDoc sc : docs.scoreDocs) { Document doc = searcher.doc(sc.doc); String entityId = doc.get( fetchRelation ? IndexingConstants.PARENT_ID_FIELD : IndexingConstants.ENTITY_ID_FIELD); String superCol = doc.get(SUPERCOLUMN_INDEX); if (superCol == null) { superCol = "SuperCol" + nullCount++; } // In case of super column and association. indexCol.put(superCol + "|" + entityId, entityId); } } } catch (Exception e) { log.error("Error while parsing Lucene Query {} ", luceneQuery, e); throw new LuceneIndexingException(e); } reader = null; return indexCol; }
From source file:com.intuit.tank.search.lucene.LuceneService.java
License:Open Source License
/** * Searches through the index for the specified query and returns the list of documents that finds a match for the * query.//from w ww . ja v a2s . c o m * * @param query * @return */ public List<Document> search(Query query, boolean prefixWildCard) { List<Document> documents = new ArrayList<Document>(); try { IndexSearcher searcher = getSearcher(); TopDocs search = searcher.search(query, 10000); for (ScoreDoc scoreDoc : search.scoreDocs) { Document doc = searcher.doc(scoreDoc.doc); documents.add(doc); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } return documents; }
From source file:com.it.lucene.test.IndexSearch.java
private void doSearch(Query query) { try {// w w w. java 2s. c om // 2?IndexSearcher // 2.1 IndexReader // 2.1Directory Directory directory = FSDirectory.open(new File("F:\\Lucene Index")); IndexReader reader = DirectoryReader.open(directory); IndexSearcher searcher = new IndexSearcher(reader); // 3?indexSearcher? // ? TopDocs topDocs = searcher.search(query, 10); // 4?? // ??? long count = topDocs.totalHits; System.out.println("???:" + count); ScoreDoc[] scoreDocs = topDocs.scoreDocs; for (ScoreDoc scoreDoc : scoreDocs) { int docId = scoreDoc.doc; Document doc = searcher.doc(docId); System.out.println("?ID" + doc.get("id")); System.out.println("???" + doc.get("name")); System.out.println("?" + doc.get("price")); System.out.println("?pic" + doc.get("pic")); } // 5?IndexReader reader.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.ivannotes.searchbee.SearchBee.java
License:Apache License
/** * ?/* w ww . j a va2 s . com*/ * * @param keyWords key words * @return List<Document> * @throws IOException */ public final List<Document> query(String keyWords, QueryBuilder queryBuilder) throws IOException { IndexSearcher idxSearcher = getIndexSearcher(); Query query = queryBuilder.buildQuery(keyWords); TopDocs topDocs = idxSearcher.search(query, MAX_RESULT); ScoreDoc[] sDocs = topDocs.scoreDocs; List<Document> resultDocs = new ArrayList<Document>(); if (null == sDocs || sDocs.length == 0) { return resultDocs; } for (int i = 0; i < sDocs.length; i++) { resultDocs.add(idxSearcher.doc(sDocs[i].doc)); } return resultDocs; }
From source file:com.ivannotes.searchbee.SearchBee.java
License:Apache License
/** * ?/*from ww w. jav a 2s . c om*/ * * @param keyWords key words * @param page ? * @param pageSize ? * @return {@link PaginationResult} * @see PaginationResult * @throws IOException */ public final PaginationResult doPaginationQuery(String keyWords, int page, int pageSize, QueryBuilder queryBuilder) throws IOException { PaginationResult result = new PaginationResult(); result.setCurrentPage(page); result.setPageSize(pageSize); IndexSearcher idxSearch = getIndexSearcher(); Query query = queryBuilder.buildQuery(keyWords); TopDocs topDocs = idxSearch.search(query, MAX_RESULT); int totalHits = topDocs.totalHits; result.setTotalHits(totalHits); int start = page * pageSize; int end = start + pageSize; List<Document> docs = new ArrayList<Document>(); ScoreDoc[] scoreDocs = topDocs.scoreDocs; result.setDocs(docs); if (null == scoreDocs || scoreDocs.length == 0) { return result; } for (int i = start; i < totalHits; i++) { if (i > (end - 1)) { break; } docs.add(idxSearch.doc(scoreDocs[i].doc)); } if (logger.isDebugEnabled()) { logger.debug(String.format("search result: totalHits-%d curPage-%d pageSize-%d", result.getTotalHits(), result.getCurrentPage(), result.getPageSize())); } return result; }
From source file:com.javapr.plaintextindex.search.Suchen.java
License:Apache License
public void sucheString(String line) throws IOException, ParseException { frame = new JFrame(); frame.setTitle("Lucene Suche"); frame.setSize(400, 180);//from w w w . j av a2 s .c o m frame.setLocation(400, 400); frame.setVisible(true); panel = new JPanel(new BorderLayout(5, 5)); list = new JList(); panel1 = new JPanel(new GridLayout(1, 1)); panelLabel = new JPanel(new GridLayout(2, 1)); pane = new JScrollPane(panel1); labelAnzData = new JLabel(); alert = new JLabel(); suche = new JLabel(); dir = new JLabel(); panel.add(panelLabel, BorderLayout.WEST); panel.add(pane, BorderLayout.CENTER); frame.add(panel); String field = "contents"; int hitsPerPage = 10; try { IndexReader indexReader = DirectoryReader.open(FSDirectory.open(new File(Prop.Indexdirectory(null)))); IndexSearcher indexSearcher = new IndexSearcher(indexReader); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_42); QueryParser parser = new QueryParser(Version.LUCENE_42, field, analyzer); list1 = new ArrayList<Object>(); try { Query query = parser.parse(line); suche = new JLabel("Suche nach: " + line); panelLabel.add(suche); TopDocs results = indexSearcher.search(query, 5 * hitsPerPage); ScoreDoc[] hits = results.scoreDocs; int end = hits.length; //Liste erzeugen und mit gefundenen Dateinamen fllen for (int i = 0; i < end; i++) { Document doc = indexSearcher.doc(hits[i].doc); String path = doc.get("filename"); File file = new File(Prop.Filestoindex(null) + "\\" + doc.get("filename")); if (path != null) { list1.add(path + ", " + file.length() / 1024 + "kb"); } } labelAnzData = new JLabel(hits.length + " Gefundene Datei(en): "); panelLabel.add(labelAnzData); list = new JList(list1.toArray()); panel1.add(list); } catch (ParseException p) { alert = new JLabel("String eingeben!"); panel.add(alert); ; } } catch (IOException e) { dir.setText("<html><body>Index-Datei nicht gefunden!<br>Bitte Index erstellen!</body></html>"); panel.add(dir); } }
From source file:com.knowgate.lucene.BugSearcher.java
License:Open Source License
/** * Compose a Lucene query based on given parameters * @param sLuceneIndexPath String Base path for Lucene indexes excluding WorkArea and table name * @param sWorkArea String GUID of WorkArea to be searched, cannot be null * @param sProject String GUID f project to which bug belongs * @param sReportedBy String//from w ww .ja va 2 s .co m * @param sWrittenBy String * @param sTitle String * @param sFromDate String * @param sToDate String * @param sType String * @param sPriority String * @param sSeverity String * @param sStatus String * @param sText String * @param sComments String * @param iLimit int * @param oSortBy Comparator * @return BugRecord[] * @throws ParseException * @throws IOException * @throws NullPointerException */ public static BugRecord[] search(String sLuceneIndexPath, String sWorkArea, String sProjectGUID, String sReportedBy, String sWrittenBy, String sTitle, Date dtFromDate, Date dtToDate, String sType, String sPriority, String sSeverity, String sStatus, String sText, String sComments, int iLimit, Comparator oSortBy) throws ParseException, IOException, NullPointerException { if (null == sLuceneIndexPath) throw new NullPointerException("BugSearcher.search() luceindex parameter cannot be null"); if (null == sWorkArea) throw new NullPointerException("BugSearcher.search() workarea parameter cannot be null"); if (DebugFile.trace) { DebugFile.writeln("Begin BugSearcher.search(" + sLuceneIndexPath + "," + sWorkArea + "," + sProjectGUID + "," + sReportedBy + "," + sWrittenBy + "," + sTitle + "," + dtFromDate + "," + dtToDate + "," + sType + "," + sPriority + "," + sSeverity + "," + "," + sStatus + "," + sText + String.valueOf(iLimit) + ")"); DebugFile.incIdent(); } BugRecord[] aRetArr; BooleanQuery oQry = new BooleanQuery(); oQry.add(new TermQuery(new Term("workarea", sWorkArea)), BooleanClause.Occur.MUST); if (null != sProjectGUID) if (sProjectGUID.length() > 0) oQry.add(new TermQuery(new Term("container", sProjectGUID)), BooleanClause.Occur.MUST); if (null != sWrittenBy) if (sWrittenBy.length() > 0) oQry.add(new TermQuery(new Term("writer", sWrittenBy)), BooleanClause.Occur.MUST); if (null != sReportedBy) if (sReportedBy.length() > 0) oQry.add(new TermQuery(new Term("author", sReportedBy)), BooleanClause.Occur.MUST); if (null != sTitle) if (sTitle.length() > 0) oQry.add(new TermQuery(new Term("title", sTitle)), BooleanClause.Occur.MUST); if (null != sType) if (sType.length() > 0) oQry.add(new TermQuery(new Term("type", sType)), BooleanClause.Occur.MUST); if (null != sStatus) if (sStatus.length() > 0) oQry.add(new TermQuery(new Term("status", sStatus)), BooleanClause.Occur.MUST); if (null != sPriority) if (sPriority.length() > 0) oQry.add(new TermQuery(new Term("priority", sPriority)), BooleanClause.Occur.MUST); if (null != sSeverity) if (sSeverity.length() > 0) oQry.add(new TermQuery(new Term("severity", sSeverity)), BooleanClause.Occur.MUST); if (dtFromDate != null && dtToDate != null) oQry.add( new TermRangeQuery("created", DateTools.dateToString(dtFromDate, DateTools.Resolution.DAY), DateTools.dateToString(dtToDate, DateTools.Resolution.DAY), true, true), BooleanClause.Occur.MUST); else if (dtFromDate != null) oQry.add(new TermRangeQuery("created", DateTools.dateToString(dtFromDate, DateTools.Resolution.DAY), null, true, false), BooleanClause.Occur.MUST); else if (dtToDate != null) oQry.add(new TermRangeQuery("created", null, DateTools.dateToString(dtToDate, DateTools.Resolution.DAY), false, true), BooleanClause.Occur.MUST); if (null != sText) if (sText.length() > 0) oQry.add(new TermQuery(new Term("text", sText)), BooleanClause.Occur.SHOULD); if (null != sComments) if (sComments.length() > 0) oQry.add(new TermQuery(new Term("comments", sComments)), BooleanClause.Occur.SHOULD); String sSegments = Gadgets.chomp(sLuceneIndexPath, File.separator) + "k_bugs" + File.separator + sWorkArea; if (DebugFile.trace) DebugFile.writeln("new IndexSearcher(" + sSegments + ")"); Directory oFsDir = Indexer.openDirectory(sSegments); IndexSearcher oSearch = new IndexSearcher(oFsDir); Document oDoc; TopDocs oTopSet = oSearch.search(oQry, null, iLimit > 0 ? iLimit : 2147483647); if (oTopSet.scoreDocs != null) { ScoreDoc[] oTopDoc = oTopSet.scoreDocs; int iDocCount = oTopDoc.length; aRetArr = new BugRecord[iDocCount]; for (int d = 0; d < iDocCount; d++) { oDoc = oSearch.doc(oTopDoc[d].doc); aRetArr[d] = new BugRecord(oTopDoc[d].score, Integer.parseInt(oDoc.get("number")), oDoc.get("guid"), oDoc.get("container"), oDoc.get("title"), oDoc.get("author"), oDoc.get("created"), oDoc.get("type"), oDoc.get("status"), oDoc.get("priority"), oDoc.get("severity"), oDoc.get("abstract")); } // next } else { aRetArr = null; } oSearch.close(); oFsDir.close(); if (oSortBy != null) { Arrays.sort(aRetArr, oSortBy); } if (DebugFile.trace) { DebugFile.decIdent(); if (null == aRetArr) DebugFile.writeln("End BugSearcher.search() : no records found"); else DebugFile.writeln("End BugSearcher.search() : " + String.valueOf(aRetArr.length)); } return aRetArr; }
From source file:com.knowgate.lucene.ContactSearcher.java
License:Open Source License
/** * Compose a Lucene query based on given parameters * @param sLuceneIndexPath String Base path for Lucene indexes excluding WorkArea and table name * @param sWorkArea String GUID of WorkArea to be searched, cannot be null * @param sProject String GUID f project to which bug belongs * @param sReportedBy String/*from w w w . j a va2s . co m*/ * @param sWrittenBy String * @param sTitle String * @param sFromDate String * @param sToDate String * @param sType String * @param sPriority String * @param sSeverity String * @param sStatus String * @param sText String * @param sComments String * @param iLimit int * @param oSortBy Comparator * @return BugRecord[] * @throws ParseException * @throws IOException * @throws NullPointerException */ public static ContactRecord[] search(Properties oProps, String sWorkArea, String values[], boolean obligatorio[]) throws ParseException, IOException, NullPointerException { if (null == oProps.getProperty("luceneindex")) throw new NullPointerException("ContactSearcher.search() luceindex parameter cannot be null"); if (null == sWorkArea) throw new NullPointerException("ContactSearcher.search() workarea parameter cannot be null"); if (DebugFile.trace) { DebugFile.writeln("Begin ContactSearcher.search(" + oProps.getProperty("luceneindex") + "," + sWorkArea + "," + String.valueOf(20) + ")"); DebugFile.incIdent(); } BooleanQuery oQry = new BooleanQuery(); oQry.add(new TermQuery(new Term("workarea", sWorkArea)), BooleanClause.Occur.MUST); for (int i = 0; i < values.length; i++) { if (obligatorio[i]) { oQry.add(new TermQuery(new Term("value", values[i])), BooleanClause.Occur.MUST); } else { oQry.add(new TermQuery(new Term("value", values[i])), BooleanClause.Occur.SHOULD); } } String sSegments = Gadgets.chomp(oProps.getProperty("luceneindex"), File.separator) + "k_contacts" + File.separator + sWorkArea; if (DebugFile.trace) DebugFile.writeln("new IndexSearcher(" + sSegments + ")"); File oDir = new File(sSegments); if (!oDir.exists()) { try { Indexer.rebuild(oProps, "k_contacts", sWorkArea); } catch (Exception e) { if (DebugFile.trace) DebugFile.writeln(e.getMessage()); } } Directory oFsDir = Indexer.openDirectory(sSegments); IndexSearcher oSearch = new IndexSearcher(oFsDir); Document oDoc; ContactRecord aRetArr[] = null; TopDocs oTopSet = oSearch.search(oQry, null, 20); if (oTopSet.scoreDocs != null) { ScoreDoc[] oTopDoc = oTopSet.scoreDocs; int iDocCount = oTopDoc.length; aRetArr = new ContactRecord[iDocCount]; for (int d = 0; d < iDocCount; d++) { oDoc = oSearch.doc(oTopDoc[d].doc); // String[] aAbstract = Gadgets.split(oSearch.doc(oTopDoc[d].doc).get("abstract"), ''); aRetArr[d] = new ContactRecord(oTopDoc[d].score, oDoc.get("author"), oDoc.get("workarea"), oDoc.get("guid"), oDoc.get("value")); } // next } else { aRetArr = null; } oSearch.close(); oFsDir.close(); if (DebugFile.trace) { DebugFile.decIdent(); if (null == aRetArr) DebugFile.writeln("End ContactSearcher.search() : no records found"); else DebugFile.writeln("End ContactSearcher.search() : " + String.valueOf(aRetArr.length)); } return aRetArr; }