How to format sum_bucket aggregation float output?

I use Elasticsearch for my Search Service and I use this JSON request for sum_bucket aggregation:

"from": 0,
    "size": 0,
    "aggregations": {
        "aggr": {
            "type": "term",
            "field": "type.keyword",
            "size": 10,
            "order": {
                "myAggr2.value": "desc"
            },
            "aggregations": {
                "myAggr2": {
                    "type": "sum",
                    "field": "length"
                }
            }
        },
        "total_myAggr2": {
            "type": "sum_bucket",
            "buckets_path": "aggr>myAggr2"
        }
    },
    "types": [
        "cable"
    ]
}

In the response I get this:

{
    "totalHits": 4,
    "tookInMillis": 1,
    "hits": [],
    "aggregations": {
        "total_myAggr2": {
            "value": "3.7600000000000002"
        },
        "aggr": {
            "sumOtherDocCount": 0,
            "buckets": [
                {
                    "key": "cable",
                    "count": 4,
                    "aggregations": {
                        "myAggr2": {
                            "value": "3.7600000000000002"
                        }
                    }
                }
            ]
        }
    }
}

Is any possibility to format the output from "3.7600000000000002" to "3.76" ? I found attribute format in ES docu but not for number formatting...

Hi,
I found format attribute described in Average Bucket Aggregation of the document. It says the format is according to Java DecimalFormat: format: "#.00".

(PS I incidentaly found the format attribute are usable in sum aggregation too.)

Thank you @Tomo_M! I have one more question... :slightly_smiling_face: Why is the result both aggregations in float format? Because I have created the index for field length with scaled_float=100 so I would expected the result as "3.76".

I'm only a user and not sure about the internal argorithm about scaled_float, but I suppose aggregation uses only its value as float regardless of numeric field types because even aggregation on integer field returns float as follows.
My guess is that the conversion to float is done before the aggregation, which is the cause of your rounding error. Note that this is just my guess :grinning:

{
"aggregations" : {
    "my_sum" : {
      "value" : 85425.0
    }
  }
}

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.