ElasticSearch script查询报错A document doesn‘t have a value for a field! Use doc[<field>].size()==0

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 field field.

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"
            }
          }
        }
      ]
    }
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值