如何捕获无效的Elasticsearch查询?

时间:2014-03-29 02:19:16

标签: java elasticsearch

如果查询无效,Elasticsearch的Java API(1.1.0)会抛出SearchPhaseExecutionException。这个例外没有“原因”,而是像这样的“消息”:

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: ""]; }

除了先查询SearchParseExceptionvalidating查询字符串之外,我如何区分无效查询与其他错误?

1 个答案:

答案 0 :(得分:1)

我建议在查询执行之前使用验证查询:

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()提供类似的内容(对于我正在尝试使用带有数字字段范围的文本的查询):

  

org.elasticsearch.index.query.QueryParsingException:[bill_d20160227t123119]无法解析; java.lang.NumberFormatException:对于输入字符串:“TEST”

有关验证API的更多信息,请访问https://www.elastic.co/guide/en/elasticsearch/reference/current/search-validate.html

希望它有所帮助!