Elasticsearch 执行查询语句时,碰到错误信息 Elasticsearch exception [type=search_phase_execution_exception, reason=all shards failed],原因及解决方法。
原因
此异常信息,顾名思义是 es 查询语句执行异常,并且在每个分片(shards)都失败,显然是执行语句的语法错误。
如果可以打印异常栈,打印可看出具体的错误类型,笔者遇到的是脚本异常,是脚本语法错误或 es 服务端升级导致语法不兼容等,具体如下:
Suppressed: ElasticsearchException[Elasticsearch exception [type=script_exception, reason=runtime error]]
at org.elasticsearch.ElasticsearchException.innerFromXContent(ElasticsearchException.java:496)
at org.elasticsearch.ElasticsearchException.fromXContent(ElasticsearchException.java:407)
at org.elasticsearch.ElasticsearchException.innerFromXContent(ElasticsearchException.java:469)
... 86 more
解决方法
将 es query dsl 打印,并在 kibana tools 或通过 curl 命令查看,一般 es 服务器返回 _script
脚本出现的问题处,笔者的如下:
{
"error" : {
"root_cause" : [
{
"type" : "script_exception",
"reason" : "runtime error",
"script_stack" : [
"org.elasticsearch.index.fielddata.ScriptDocValues$Longs.get(ScriptDocValues.java:121)",
"org.elasticsearch.index.fielddata.ScriptDocValues$Longs.getValue(ScriptDocValues.java:115)",
"if(doc['city_id'].value==params.city_id){",
" ^---- HERE"
],
"script" : "if(doc['city_id'].value==params.city_id){return 2;}if(doc['province_id'].size()>0){if(doc['province_id']==params.province_id){return 1;}}return 0;",
"lang" : "painless",
"position" : {
"offset" : 17,
"start" : 0,
"end" : 44
}
}
],
"type" : "search_phase_execution_exception",
"reason" : "all shards failed",
"phase" : "query",
"grouped" : true,
......
}
}
由于 es 升级之后,可无值的字段采用 value
取值是不可用,需要先通过 size()>0
判断是否可用后再使用。