# Bucket\_script inside filter aggregation throws error

**URL:** <https://discuss.elastic.co/t/bucket-script-inside-filter-aggregation-throws-error/85545>\
**Category:** Elasticsearch\
**Created:** [May 12, 2017, 10:44am UTC](https://discuss.elastic.co/t/bucket-script-inside-filter-aggregation-throws-error/85545 "2017-05-12T10:44:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![liorg2](https://avatars.discourse-cdn.com/v4/letter/l/ed8c4c/32.png) [@liorg2](https://discuss.elastic.co/u/liorg2)\
**Post date:** [May 12, 2017, 10:44am UTC](https://discuss.elastic.co/t/bucket-script-inside-filter-aggregation-throws-error/85545/1 "2017-05-12T10:44:12Z")

</div>

I am trying to filter empty buckets in side a filter aggregation block, and I get an error from elasticsearch. without this the response is huge, as I am querying lots of metric, and nested aggregation (this is part of bigger query for simplicity )

```
GET index/type/_search?ignore_unavailable
{
  "size": 0,
  "aggs": {
    "groupby_country": {
      "terms": {
        "field": "country",
        "size": 2000
      },
      "aggs": {
        "exists __x__ filter": {
          "filter": {
            "bool": {
              "filter": [
                {
                  "exists": {
                    "field": "x"
                  }
                }
              ]
            }
          },
          "aggs": {
            "sum": {
              "sum": {
                "script": "def val = doc['x'].value; if(val>0) Math.min(val , 20000)"
              }
            },
            "average_distinct": {
              "bucket_script": {
                "buckets_path": {
                  "count": "_count"
                },
                "script": "return params.count "
              }
            }
          }
        }
      }
    }
  }
}

```

elastic response:

```
{
  "error": {
    "root_cause": [],
    "type": "reduce_search_phase_exception",
    "reason": "[reduce] ",
    "phase": "fetch",
    "grouped": true,
    "failed_shards": [],
    "caused_by": {
      "type": "class_cast_exception",
      "reason": "org.elasticsearch.search.aggregations.bucket.filter.InternalFilter cannot be cast to org.elasticsearch.search.aggregations.InternalMultiBucketAggregation"
    }
  },
  "status": 503
}
```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [June 9, 2017, 10:52am UTC](https://discuss.elastic.co/t/bucket-script-inside-filter-aggregation-throws-error/85545/2 "2017-06-09T10:52:30Z")

</div>

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