# Filtering buckets in aggregation

**URL:** <https://discuss.elastic.co/t/filtering-buckets-in-aggregation/85500>\
**Category:** Elasticsearch\
**Created:** [May 12, 2017, 3:55am UTC](https://discuss.elastic.co/t/filtering-buckets-in-aggregation/85500 "2017-05-12T03:55:36Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jkthetechie](https://avatars.discourse-cdn.com/v4/letter/j/f08c70/32.png) [@jkthetechie](https://discuss.elastic.co/u/jkthetechie)\
**Post date:** [May 12, 2017, 3:55am UTC](https://discuss.elastic.co/t/filtering-buckets-in-aggregation/85500/1 "2017-05-12T03:55:36Z")

</div>

POST assetdefinition\_test/\_search  
{  
"size":0,  
"aggs":{  
"name":{  
"terms":{  
"field":"[AssetType.Name](http://AssetType.Name)",  
"size":0  
},  
"aggs":{  
"avg\_price":{  
"avg":{  
"field":"Price"}  
}  
}   
}  
}  
}

I have a aggregation query like above where it fetches the "average price" of assets aggregated (bucketed) by name.

But, I need to select only those buckets whose average price is greater than some value (say 100). How to add that filter condition. (similar to 'having' in sql).

---

<div class="post-metadata">

**Author:** ![Mark\_Harwood](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/mark_harwood/32/10538_2.png) [@Mark\_Harwood](https://discuss.elastic.co/u/Mark_Harwood)\
**Post date:** [May 12, 2017, 8:18am UTC](https://discuss.elastic.co/t/filtering-buckets-in-aggregation/85500/2 "2017-05-12T08:18:48Z")

</div>

It is important to point out that this is a problematic query in a distributed system with many unique values for the joining key.

However, given you are talking about asset _types_ as opposed to asset _IDs_ I assume there is a small number of these (\< 1000?).

If true then the following should work for you at small scales: [https://gist.github.com/markharwood/5f217da5b42525a886b3e405214e9cd7](https://gist.github.com/markharwood/5f217da5b42525a886b3e405214e9cd7)

Doing this sort of aggregation will not scale for high-cardinality fields like asset ID on a distributed system [will introduce problems](https://youtu.be/yBf7oeJKH2Y?t=3m2s) . The solution to that would be to build entity-centric indexes at index time or use multiple queries and [term partitioning](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html#_filtering_values_with_partitions)

---

<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, 8:21am UTC](https://discuss.elastic.co/t/filtering-buckets-in-aggregation/85500/3 "2017-06-09T08:21:49Z")

</div>

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