ES版本7.6.0
想筛选某两个字段之和大于10的文档,需要用到脚本,简化的请求如下
{
"query":
{
"bool":
{
"must":
[
{
"script":
{
"script": "doc['field'].value >= 1"
}
}
]
}
}
}
报非法状态异常,其实报错提示大概也讲清楚了,“A document doesn’t have a value for a field!”(有一个文档的字段没有值),不过总觉得指示清楚哪个文档哪个字段不是更友好么;并且也给出了解决方案:用doc[<field>].size()==0
检查文档是否缺失字段
{
"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)",
"doc[\"field\"].value >= 1",
" ^---- HERE"
],
"script" : "doc[\"field\"].value >= 1",
"lang" : "painless"
}
],
"type" : "search_phase_execution_exception",
"reason" : "all shards failed",
"phase" : "query",
"grouped" : true,
"failed_shards" : [
{
"shard" : 0,
"index" : "...",
"node" : "...",
"reason" : {
"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)",
"doc[\"field\"].value >= 1",
" ^---- HERE"
],
"script" : "doc[\"field\"].value >= 1",
"lang" : "painless",
"caused_by" : {
"type" : "illegal_state_exception",
"reason" : "A document doesn't have a value for a field! Use doc[<field>].size()==0 to check if a document is missing a field!"
}
}
}
]
},
"status" : 400
}
ES7.0更新中也提到了
Accessing missing document values will throw an error
doc['field'].value
will throw an exception if the document is missing a value for the fieldfield
.To check if a document is missing a value, you can use
doc['field'].size() == 0
.
解决方法:加入空检查
{
"query":
{
"bool":
{
"must":
[
{
"script":
{
"script":
{
"source": "doc[\"field\"].size() != 0 && doc[\"field\"].value > 1"
}
}
}
]
}
}
}