Reputation: 3624
Given an invalid query, Elasticsearch's Java API (1.1.0) throws a SearchPhaseExecutionException
. This exception has no "cause", but a "message" like this one:
Failed to execute phase [query_fetch], all shards failed; shardFailures {[bwUSN171Ru6rY1-su5-48A][f2f0i20hrf][0]: SearchParseException[[f2f0i20hrf][0]: from[-1],size[0]: Parse Failure [Failed to parse source [{"size":0,"query":{"bool":{"must":{"term":{"count":""}}}}}]]]; nested: NumberFormatException[For input string: ""]; }
How can I distinguish invalid queries from other errors, other than doing a string search for SearchParseException
, or validating the query first?
Upvotes: 2
Views: 1765
Reputation: 7713
I would suggest to use validate query before query execution in that case:
ValidateQueryRequest validateQueryRequest = new ValidateQueryRequest(indexName);
validateQueryRequest.source(jsonContent);
validateQueryRequest.explain(true);
ActionFuture<ValidateQueryResponse> future = client.admin().indices().validateQuery(validateQueryRequest); // the client is org.elasticsearch.client.Client
ValidateQueryResponse response = future.get(); // typical java future as response
System.out.println(response.isValid()); // true or false
System.out.println(response.getQueryExplanation().size()); // size of explanations why the query is incorrect
QueryExplanation.getError() provides something like that (for the query where I'm trying to use text with number field range):
org.elasticsearch.index.query.QueryParsingException: [bill_d20160227t123119] Failed to parse; java.lang.NumberFormatException: For input string: "TEST"
More about validation API you will find at https://www.elastic.co/guide/en/elasticsearch/reference/current/search-validate.html
Hope it helps!
Upvotes: 1