use of org.apache.lucene.queryparser.classic.ParseException in project incubator-atlas by apache.
the class QueryFactory method create.
private QueryExpression create(Request request, ResourceDefinition resourceDefinition) throws InvalidQueryException {
String queryString;
if (request.getCardinality() == Request.Cardinality.INSTANCE) {
String idPropertyName = resourceDefinition.getIdPropertyName();
queryString = String.format("%s:%s", idPropertyName, request.<String>getProperty(idPropertyName));
} else {
queryString = request.getQueryString();
}
QueryExpression queryExpression;
if (queryString != null && !queryString.isEmpty()) {
QueryParser queryParser = new QueryParser(Version.LUCENE_48, "name", new KeywordAnalyzer());
queryParser.setLowercaseExpandedTerms(false);
queryParser.setAllowLeadingWildcard(true);
Query query;
try {
query = queryParser.parse((String) escape(queryString));
} catch (ParseException e) {
throw new InvalidQueryException(e.getMessage());
}
LOG.info("LuceneQuery: {}", query);
queryExpression = create(query, resourceDefinition);
} else {
queryExpression = new AlwaysQueryExpression();
}
// add query properties to request so that they are returned
request.addAdditionalSelectProperties(queryExpression.getProperties());
return queryExpression;
}
use of org.apache.lucene.queryparser.classic.ParseException in project jackrabbit-oak by apache.
the class LuceneIndex method getLuceneRequest.
/**
* Get the Lucene query for the given filter.
*
* @param filter the filter, including full-text constraint
* @param reader the Lucene reader
* @param nonFullTextConstraints whether non-full-text constraints (such a
* path, node type, and so on) should be added to the Lucene
* query
* @param indexDefinition nodestate that contains the index definition
* @return the Lucene query
*/
private static LuceneRequestFacade getLuceneRequest(Filter filter, IndexReader reader, boolean nonFullTextConstraints, IndexDefinition indexDefinition) {
List<Query> qs = new ArrayList<Query>();
Analyzer analyzer = indexDefinition.getAnalyzer();
FullTextExpression ft = filter.getFullTextConstraint();
if (ft == null) {
// there might be no full-text constraint
// when using the LowCostLuceneIndexProvider
// which is used for testing
} else {
qs.add(getFullTextQuery(ft, analyzer, reader));
}
PropertyRestriction pr = filter.getPropertyRestriction(NATIVE_QUERY_FUNCTION);
if (pr != null) {
String query = String.valueOf(pr.first.getValue(pr.first.getType()));
QueryParser queryParser = new QueryParser(VERSION, "", indexDefinition.getAnalyzer());
if (query.startsWith("mlt?")) {
String mltQueryString = query.replace("mlt?", "");
if (reader != null) {
Query moreLikeThis = MoreLikeThisHelper.getMoreLikeThis(reader, analyzer, mltQueryString);
if (moreLikeThis != null) {
qs.add(moreLikeThis);
}
}
}
if (query.startsWith("spellcheck?")) {
String spellcheckQueryString = query.replace("spellcheck?", "");
if (reader != null) {
return new LuceneRequestFacade<SpellcheckHelper.SpellcheckQuery>(SpellcheckHelper.getSpellcheckQuery(spellcheckQueryString, reader));
}
} else if (query.startsWith("suggest?")) {
String suggestQueryString = query.replace("suggest?", "");
if (reader != null) {
return new LuceneRequestFacade<SuggestHelper.SuggestQuery>(SuggestHelper.getSuggestQuery(suggestQueryString));
}
} else {
try {
qs.add(queryParser.parse(query));
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
} else if (nonFullTextConstraints) {
addNonFullTextConstraints(qs, filter, reader, analyzer, indexDefinition);
}
if (qs.size() == 0) {
return new LuceneRequestFacade<Query>(new MatchAllDocsQuery());
}
return LucenePropertyIndex.performAdditionalWraps(qs);
}
use of org.apache.lucene.queryparser.classic.ParseException in project Anserini by castorini.
the class Rm3Reranker method rerank.
@Override
public ScoredDocuments rerank(ScoredDocuments docs, RerankerContext context) {
Preconditions.checkState(docs.documents.length == docs.scores.length);
IndexSearcher searcher = context.getIndexSearcher();
IndexReader reader = searcher.getIndexReader();
FeatureVector qfv = FeatureVector.fromTerms(AnalyzerUtils.tokenize(analyzer, context.getQueryText())).scaleToUnitL1Norm();
FeatureVector rm = estimateRelevanceModel(docs, reader);
LOG.info("Relevance model estimated.");
rm = FeatureVector.interpolate(qfv, rm, originalQueryWeight);
StringBuilder builder = new StringBuilder();
Iterator<String> terms = rm.iterator();
while (terms.hasNext()) {
String term = terms.next();
double prob = rm.getFeatureWeight(term);
builder.append(term + "^" + prob + " ");
}
String queryText = builder.toString().trim();
QueryParser p = new QueryParser(field, new WhitespaceAnalyzer());
Query nq = null;
try {
nq = p.parse(queryText);
} catch (ParseException e) {
e.printStackTrace();
return docs;
}
LOG.info("Running new query: " + nq);
TopDocs rs = null;
try {
if (context.getFilter() == null) {
rs = searcher.search(nq, 1000);
} else {
BooleanQuery.Builder bqBuilder = new BooleanQuery.Builder();
bqBuilder.add(context.getFilter(), BooleanClause.Occur.FILTER);
bqBuilder.add(nq, BooleanClause.Occur.MUST);
Query q = bqBuilder.build();
rs = searcher.search(q, 1000);
}
} catch (IOException e) {
e.printStackTrace();
return docs;
}
return ScoredDocuments.fromTopDocs(rs, searcher);
}
use of org.apache.lucene.queryparser.classic.ParseException in project Anserini by castorini.
the class TweetSearcher method main.
public static void main(String[] args) throws IOException, InterruptedException, ParseException {
Options options = new Options();
options.addOption(INDEX_OPTION, true, "index path");
options.addOption(PORT_OPTION, true, "port");
CommandLine cmdline = null;
CommandLineParser parser = new GnuParser();
try {
cmdline = parser.parse(options, args);
} catch (org.apache.commons.cli.ParseException e) {
System.err.println("Error parsing command line: " + e.getMessage());
System.exit(-1);
}
if (!cmdline.hasOption(INDEX_OPTION)) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(TweetSearcher.class.getName(), options);
System.exit(-1);
}
int port = cmdline.hasOption(PORT_OPTION) ? Integer.parseInt(cmdline.getOptionValue(PORT_OPTION)) : 8080;
TweetSearcher nrtsearch = new TweetSearcher(cmdline.getOptionValue(INDEX_OPTION));
TweetStreamIndexer its = new TweetStreamIndexer();
Thread itsThread = new Thread(its);
itsThread.start();
LOG.info("Starting HTTP server on port " + port);
HandlerList mainHandler = new HandlerList();
Server server = new Server(port);
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setWelcomeFiles(new String[] { "index.html" });
resource_handler.setResourceBase("src/main/java/io/anserini/nrts/public");
ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SESSIONS);
handler.setContextPath("/");
ServletHolder jerseyServlet = new ServletHolder(ServletContainer.class);
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", TweetSearcherAPI.class.getCanonicalName());
handler.addServlet(jerseyServlet, "/*");
mainHandler.addHandler(resource_handler);
mainHandler.addHandler(handler);
server.setHandler(mainHandler);
try {
server.start();
LOG.info("Accepting connections on port " + port);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
server.join();
itsThread.join();
nrtsearch.close();
}
use of org.apache.lucene.queryparser.classic.ParseException in project fess by codelibs.
the class QueryHelper method buildBaseQuery.
public void buildBaseQuery(final QueryContext queryContext, final Consumer<QueryContext> context) {
try {
final Query query = getQueryParser().parse(queryContext.getQueryString());
final QueryBuilder queryBuilder = convertQuery(queryContext, query, 1.0f);
if (queryBuilder != null) {
queryContext.setQueryBuilder(queryBuilder);
} else {
queryContext.setQueryBuilder(QueryBuilders.matchAllQuery());
}
// TODO options query
context.accept(queryContext);
} catch (final ParseException e) {
throw new InvalidQueryException(messages -> messages.addErrorsInvalidQueryParseError(UserMessages.GLOBAL_PROPERTY_KEY), "Invalid query: " + queryContext.getQueryString(), e);
}
}
Aggregations