Example usage for org.apache.lucene.queryparser.flexible.standard StandardQueryParser parse

List of usage examples for org.apache.lucene.queryparser.flexible.standard StandardQueryParser parse

Introduction

In this page you can find the example usage for org.apache.lucene.queryparser.flexible.standard StandardQueryParser parse.

Prototype

@Override
public Query parse(String query, String defaultField) throws QueryNodeException 

Source Link

Document

Overrides QueryParserHelper#parse(String,String) so it casts the return object to Query .

Usage

From source file:com.netcrest.pado.index.provider.lucene.LuceneSearch.java

License:Open Source License

protected Set<Object> getIdentityKeySet(String queryString, Directory dir) {
    Set<Object> identityKeySet = new HashSet<Object>();
    DirectoryReader reader;//from w  w  w  .j  a v a2  s. co  m
    try {
        reader = DirectoryReader.open(dir);
    } catch (CorruptIndexException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
    } catch (IOException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
    }

    Query query;
    try {
        StandardQueryParser parser = new StandardQueryParser(new StandardAnalyzer(LUCENE_VERSION));
        query = parser.parse(queryString.replaceAll("\\-", "\\\\-"), "__doc");
    } catch (Exception ex) {
        // Lucene bug. Unable to serialize exception. Log the message and
        // throw a new exception with the string message.
        ex.printStackTrace();
        throw new PadoException(ex.getMessage());
    }
    IndexSearcher searcher = new IndexSearcher(reader);
    TopDocs results;
    try {
        results = searcher.search(query, null, Integer.MAX_VALUE);

        for (ScoreDoc hit : results.scoreDocs) {
            Document doc;
            try {
                doc = searcher.doc(hit.doc);
            } catch (CorruptIndexException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
            //            IndexableField field = doc.getField("IdentityKey");
            //            if (field == null) {
            //               continue;
            //            }
            //            Object identityKey = field.stringValue();
            //            if (identityKey == null) {
            //               identityKey = field.numericValue();
            //            }
            //            if (identityKey == null) {
            //               BytesRef br = field.binaryValue();
            //               if (br != null) {
            //                  byte[] blob = br.bytes;
            //                  try {
            //                     identityKey = BlobHelper.deserializeBlob(blob);
            //                     identityKeySet.add(identityKey);
            //                  } catch (Exception ex) {
            //                     Logger.warning("Identity key deserialization error", ex);
            //                  }
            //               } else {
            //                  identityKey = field.toString();
            //               }
            //            }
            LuceneField luceneField = new LuceneField();
            ITemporalKey temporalKey = luceneField.getTemporalKey(doc);
            if (temporalKey != null) {
                identityKeySet.add(temporalKey.getIdentityKey());
            }
        }
    } catch (IOException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
    }
    return identityKeySet;
}

From source file:com.netcrest.pado.index.provider.lucene.LuceneSearch.java

License:Open Source License

protected Set<ITemporalKey> getTemporalKeySet(String queryString, Directory dir) {
    Set<ITemporalKey> temporalKeySet = new HashSet<ITemporalKey>();
    DirectoryReader reader;//from   w w  w  .  j  a va 2s  . c o  m
    try {
        reader = DirectoryReader.open(dir);
    } catch (CorruptIndexException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
    } catch (IOException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
    }
    Query query;
    try {
        StandardQueryParser parser = new StandardQueryParser(new StandardAnalyzer(LUCENE_VERSION));
        query = parser.parse(queryString.replaceAll("\\-", "\\\\-"), "__doc");
    } catch (Exception ex) {
        // Lucene 4.7 bug, internal message not serializable
        // Send message instead of nesting the cause.
        throw new RuntimeException(ex.getMessage());
    }

    IndexSearcher searcher = new IndexSearcher(reader);
    TopDocs results;
    try {
        results = searcher.search(query, null, Integer.MAX_VALUE);

        for (ScoreDoc hit : results.scoreDocs) {
            Document doc;
            try {
                doc = searcher.doc(hit.doc);
            } catch (CorruptIndexException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
            LuceneField luceneField = new LuceneField();
            ITemporalKey temporalKey = luceneField.getTemporalKey(doc);
            if (temporalKey != null) {
                temporalKeySet.add(temporalKey);
            }
        }
    } catch (IOException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
    }
    return temporalKeySet;
}

From source file:com.netcrest.pado.index.provider.lucene.TopNLuceneSearch.java

License:Open Source License

protected Set<Object> getIdentityKeySet(String queryString, Directory dir) {
    Set<Object> identityKeySet = new HashSet<Object>();
    DirectoryReader reader;/*w ww  .ja va 2s  . c o  m*/
    try {
        reader = DirectoryReader.open(dir);
    } catch (CorruptIndexException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
    } catch (IOException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
    }

    Query query;
    try {
        StandardQueryParser parser = new StandardQueryParser(new StandardAnalyzer(LUCENE_VERSION));
        query = parser.parse(queryString.replaceAll("\\-", "\\\\-"), "__doc");
    } catch (Exception ex) {
        // Lucene bug. Unable to serialize exception. Log the message and
        // throw a new exception with the string message.
        ex.printStackTrace();
        throw new PadoException(ex.getMessage());
    }
    IndexSearcher searcher = new IndexSearcher(reader);
    TopDocs results;
    try {
        results = searcher.search(query, null, Integer.MAX_VALUE);
        for (ScoreDoc hit : results.scoreDocs) {
            Document doc;
            try {
                doc = searcher.doc(hit.doc);
            } catch (CorruptIndexException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
            // IndexableField field = doc.getField("IdentityKey");
            // if (field == null) {
            // continue;
            // }
            // Object identityKey = field.stringValue();
            // if (identityKey == null) {
            // identityKey = field.numericValue();
            // }
            // if (identityKey == null) {
            // BytesRef br = field.binaryValue();
            // if (br != null) {
            // byte[] blob = br.bytes;
            // try {
            // identityKey = BlobHelper.deserializeBlob(blob);
            // identityKeySet.add(identityKey);
            // } catch (Exception ex) {
            // Logger.warning("Identity key deserialization error", ex);
            // }
            // } else {
            // identityKey = field.toString();
            // }
            // }
            LuceneField luceneField = new LuceneField();
            ITemporalKey temporalKey = luceneField.getTemporalKey(doc);

            if (temporalKey != null) {
                float docScore = hit.score;
                identityKeySet.add(temporalKey.getIdentityKey());
            }
        }
    } catch (IOException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
    }
    return identityKeySet;
}

From source file:com.tuplejump.stargate.lucene.query.LuceneCondition.java

License:Apache License

/**
 * {@inheritDoc}//from   w  w w . jav a 2s.c o  m
 */
@Override
public Query query(Options schema) {
    if (query == null) {
        throw new IllegalArgumentException("Query statement required");
    }
    try {
        StandardQueryParser parser = new StandardQueryParser(schema.analyzer);
        parser.setNumericConfigMap(schema.numericFieldOptions);
        parser.setAllowLeadingWildcard(true);
        Query luceneQuery = parser.parse(query, getDefaultField(schema));
        luceneQuery.setBoost(boost);
        logger.debug("Lucene query is {}", luceneQuery);
        return luceneQuery;
    } catch (Exception e) {
        throw new RuntimeException("Error while parsing lucene syntax query", e);
    }
}

From source file:de.walware.statet.r.internal.core.rhelp.index.SearchQuery.java

License:Open Source License

static Query createMainQuery(final String fields[], final String queryText) throws QueryNodeException {
    final StandardQueryParser p = new StandardQueryParser(QUERY_ANALYZER);
    p.setDefaultOperator(Operator.AND);/* w  ww  .  j  a  v  a 2s.  co  m*/
    p.setAllowLeadingWildcard(true);
    p.setMultiFields(fields);
    return p.parse(queryText, null);
}

From source file:edu.utsa.sifter.IndexResource.java

License:Apache License

Query parseQuery(final String queryString, final String defaultField) throws QueryNodeException {
    if (queryString != null && !queryString.isEmpty()) {
        StandardQueryParser qp = new StandardQueryParser();
        return qp.parse(queryString, defaultField);
    } else {/*from w w w  .ja v  a 2s. com*/
        return new MatchAllDocsQuery();
    }
}

From source file:eu.europeana.corelib.search.utils.SearchUtils.java

License:Creative Commons License

public static boolean isTermQuery(String queryTerm) {
    StandardQueryParser queryParserHelper = new StandardQueryParser();
    org.apache.lucene.search.Query query = null;
    try {//from   www. ja  va  2  s.  com
        query = queryParserHelper.parse(queryTerm, "text");
    } catch (QueryNodeException e) {
        //e.printStackTrace();
    }
    return (query != null && query instanceof TermQuery);
}

From source file:intelligentWebAlgorithms.examples.search.MySearcher.java

License:Apache License

public SearchResult[] search(String query, int numberOfMatches) {

    SearchResult[] docResults = null;

    IndexSearcher is = null;/*w ww .  ja va  2s .  co  m*/

    Directory dir = null;
    try {
        dir = FSDirectory.open(indexFile);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    DirectoryReader dirReader = null;
    try {

        dirReader = DirectoryReader.open(dir);
        is = new IndexSearcher(dirReader);

    } catch (IOException ioX) {
        System.out.println("ERROR: " + ioX.getMessage());
    }

    StandardQueryParser queryParserHelper = new StandardQueryParser();
    Query q = null;

    try {

        q = queryParserHelper.parse(query, LuceneIndexBuilder.INDEX_FIELD_CONTENT);

    } catch (QueryNodeException e) {
        e.printStackTrace();
    }

    TopDocs hits = null;
    try {
        hits = is.search(q, numberOfMatches);

        docResults = new SearchResult[hits.scoreDocs.length];

        for (int i = 0; i < hits.scoreDocs.length; i++) {

            Document hitDoc = is.doc(hits.scoreDocs[i].doc);

            docResults[i] = new SearchResult(hitDoc.get("docid"), hitDoc.get("doctype"), hitDoc.get("title"),
                    hitDoc.get("url"), hits.scoreDocs[i].score);
        }

        dirReader.close();
        dir.close();

    } catch (IOException ioX) {
        System.out.println("ERROR: " + ioX.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
    }

    String header = "Search results using Lucene index scores:";
    boolean showTitle = true;
    printResults(header, "Query: " + query, docResults, showTitle);

    return docResults;
}

From source file:io.anserini.rerank.lib.AxiomReranker.java

License:Apache License

@Override
public ScoredDocuments rerank(ScoredDocuments docs, RerankerContext<T> context) {
    assert (docs.documents.length == docs.scores.length);

    try {/*from   ww  w .  j  a  v  a 2 s  .c  o  m*/
        // First to search against external index if it is not null
        docs = processExternalContext(docs, context);
        // Select R*M docs from the original ranking list as the reranking pool
        Set<Integer> usedDocs = selectDocs(docs, context);
        // Extract an inverted list from the reranking pool
        Map<String, Set<Integer>> termInvertedList = extractTerms(usedDocs, context, null);
        // Calculate all the terms in the reranking pool and pick top K of them
        Map<String, Double> expandedTermScores = computeTermScore(termInvertedList, context);
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Double> termScore : expandedTermScores.entrySet()) {
            String term = termScore.getKey();
            double score = termScore.getValue();
            builder.append(term).append("^").append(score).append(" ");
        }
        String queryText = builder.toString().trim();

        if (queryText.isEmpty()) {
            LOG.info("[Empty Expanded Query]: " + context.getQueryTokens());
            queryText = context.getQueryText();
        }

        StandardQueryParser p = new StandardQueryParser();
        Query nq = p.parse(queryText, this.field);

        if (this.outputQuery) {
            LOG.info("QID: " + context.getQueryId());
            LOG.info("Original Query: " + context.getQuery().toString(this.field));
            LOG.info("Running new query: " + nq.toString(this.field));
        }

        return searchTopDocs(nq, context);
    } catch (Exception e) {
        e.printStackTrace();
        return docs;
    }
}

From source file:io.vertigo.dynamo.plugins.collections.lucene.RamLuceneQueryFactory.java

License:Apache License

private static Query createFilteredQuery(final Analyzer queryAnalyser, final Query keywordsQuery,
        final List<ListFilter> filters) {
    final Builder queryBuilder = new BooleanQuery.Builder().add(keywordsQuery, BooleanClause.Occur.MUST);

    final StandardQueryParser queryParser = new StandardQueryParser(queryAnalyser);
    for (final ListFilter filter : filters) {
        try {/*from ww w. ja  v a  2s . c  o m*/
            queryBuilder.add(queryParser.parse(filter.getFilterValue(), null),
                    isExclusion(filter) ? BooleanClause.Occur.MUST_NOT : BooleanClause.Occur.MUST);
        } catch (final QueryNodeException e) {
            throw WrappedException.wrap(e, "Erreur lors de la cration du filtrage de la requete");
        }
    }
    return queryBuilder.build();
}