# Error for scripted\_metric aggregation on auto\_date\_histogram aggregation

**URL:** <https://discuss.elastic.co/t/error-for-scripted-metric-aggregation-on-auto-date-histogram-aggregation/296741>\
**Category:** Elasticsearch\
**Tags:** painless\
**Created:** [February 9, 2022, 3:05pm UTC](https://discuss.elastic.co/t/error-for-scripted-metric-aggregation-on-auto-date-histogram-aggregation/296741 "2022-02-09T15:05:26Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![Tomo\_M](https://avatars.discourse-cdn.com/v4/letter/t/848f3c/32.png) [@Tomo\_M](https://discuss.elastic.co/u/Tomo_M)\
**Post date:** [February 9, 2022, 5:11pm UTC](https://discuss.elastic.co/t/error-for-scripted-metric-aggregation-on-auto-date-histogram-aggregation/296741/2 "2022-02-09T17:11:27Z")

</div>

I'm not sure why, it worked for `terms` bucket aggregation.  
But It failed for `histogram` aggregation as for `date histogram` aggregation.

Something is wrong when `s`, which is supposed to be a `HashMap` (or possibly `null`), has become `Long`.  
Could this be a bug of scripted\_metric aggregation on both histogram aggregations??

```auto
GET kibana_sample_data_logs/_search?size=0
{
  "query": {
    "match_all": {}
  },
  "aggs": {
    "doc_buckets_for_date_histogram": {
      "terms": {
        "field": "agent.keyword"
      },
      "aggs": {
        "max_bytes": {
          "scripted_metric": {
            "init_script": "state.max_bytes = 0L;", 
            "map_script": """ 
              def current_bytes = doc['bytes'].getValue();
              if (current_bytes > state.max_bytes)
                {state.max_bytes = current_bytes;}
            """,
            "combine_script": "return state", 
            "reduce_script": """ 
              def max_bytes = 0L;
              for (s in states) {if (s.max_bytes > (max_bytes))
                {max_bytes = s.max_bytes;}}
              return max_bytes
            """
          }
        }   
      }
    }
  }
}

```

I found a similar post of several years ago left unsolved...

> [@Scriptet metric aggregation as sub aggregation after date histogram](https://discuss.elastic.co/t/scriptet-metric-aggregation-as-sub-aggregation-after-date-histogram/61579):
>
> Hi, I'm trying to use a scripted metric aggregation as sub aggregation after a date histogram aggregation and I'm getting some errors: 'Cannot invoke method getAt() on null object' If I do this same scripted metric aggregation after another type of bucket aggregation (non date histogram) then everything works. Does anybody know why this type of query is failing after a date histogram aggregation? script: { \_ "query":{\_ \_ "bool": {\_ \_ "must": [\_ \_ {"boo…

---

_[View the full topic](https://discuss.elastic.co/t/error-for-scripted-metric-aggregation-on-auto-date-histogram-aggregation/296741)._
