在ElasticSearch中使用内联脚本时,如何检查字段数据是数字

时间:2016-08-08 04:14:16

标签: elasticsearch

根据我们的要求,我们需要在添加新文档之前找到文档的最大ID。这里的问题是doc可能包含字符串数据也因此必须在弹性查询上使用内联脚本才能找到具有整数数据的文档的最大id,否则返回0. am使用下面的内联脚本查询来查找max-key但不能正常工作。你可以帮助我吗?。

{
  "size":0,
  "query":
  {"bool":
    {"filter":[
      {"term":
        {"Name":
          {
            "value":"Test2"
          }
        }}
          ]
    }},
          "aggs":{
            "MaxId":{
              "max":{
                "field":"Key","script":{
                  "inline":"((doc['Key'].value).isNumber()) ? Integer.parseInt(doc['Key'].value) : 0"}}
            }
          }
}

1 个答案:

答案 0 :(得分:0)

错误是因为max aggregation仅支持数字字段,即您无法在max aggregation中指定字符串字段(即Key)。

只需删除"field":"Key"部分,只保留脚本部分

{
  "size": 0,
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "Name": "Test2"
          }
        }
      ]
    }
  },
  "aggs": {
    "MaxId": {
      "max": {
        "script": {
          "inline": "((doc['Key'].value).isNumber()) ? Integer.parseInt(doc['Key'].value) : 0"
        }
      }
    }
  }
}
相关问题