在聚合时将字符串转换为浮点数? [英] Convert strings to floats at aggregation time?

查看:29
本文介绍了在聚合时将字符串转换为浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在指定直方图聚合时,有什么方法可以将字符串转换为浮点数?因为我的文档中的字段是浮点数但没有被 elasticsearch 解析,当我尝试使用字符串字段进行求和时,它会引发下一个错误.

Is there any way to convert strings to floats when specifying a histogram aggregation? Because I have documents with fields that are floats but are not parsed by elasticsearch as such, and when I attempt to do a sum using a string field It throws the next error.

ClassCastException[org.elasticsearch.index.fielddata.plain.PagedBytesIndexFieldData 
cannot be cast to org.elasticsearch.index.fielddata.IndexNumericFieldData]}]"

我知道我可以更改映射,但是对于我的用例,如果我这样做会更方便在编写字段的聚合.

I know I could change the mapping, but for the usage case that I have, it would be more handy if I could specify something like "script : _value.tofloat()" when writing the aggregation for the field.

这是我的代码:

{
"query" : {
    "bool": {"
         must": [
            {"match": { "sensorId":  "D14UD021808ARZC" }},
            {"match": { "variableName": "CAUDAL"}}
        ]
    }
},      
"aggs" : {
    "caudal_per_month" : {
          "date_histogram" : {
                  "field" : "timestamp",
                  "interval" : "month"
          },
          "aggs": {
             "totalmonth": {
                    "sum": {
                        "field": "value",
                        "script" : "_value*1.0"
                    }
             }
         }
    }
}  

}

推荐答案

你需要这个

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "sensorId": "D14UD021808ARZC"
          }
        },
        {
          "match": {
            "variableName": "CAUDAL"
          }
        }
      ]
    }
  },
  "aggs": {
    "caudal_per_month": {
      "date_histogram": {
        "field": "timestamp",
        "interval": "month"
      },
      "aggs": {
        "totalmonth": {
          "sum": {
            "script": "Float.parseFloat(doc['value'].value)"
          }
        }
      }
    }
  }
}

对于名为 value 的字段:Float.parseFloat(doc['value'].value)

这篇关于在聚合时将字符串转换为浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆