# Pipeline aggregations: Sorting/Filtering after bucket\_script execution

**URL:** <https://discuss.elastic.co/t/pipeline-aggregations-sorting-filtering-after-bucket-script-execution/365786>\
**Category:** Elasticsearch\
**Created:** [August 29, 2024, 4:30pm UTC](https://discuss.elastic.co/t/pipeline-aggregations-sorting-filtering-after-bucket-script-execution/365786 "2024-08-29T16:30:20Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![spinscale](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/spinscale/32/25011_2.png) [@spinscale](https://discuss.elastic.co/u/spinscale)\
**Post date:** [August 29, 2024, 4:30pm UTC](https://discuss.elastic.co/t/pipeline-aggregations-sorting-filtering-after-bucket-script-execution/365786/1 "2024-08-29T16:30:21Z")

</div>

Hey,

I am running an aggregation that groups by a terms aggregation and then runs the sum on a field for each bucket. Works of course.

Now on top of that I have a bucket script aggregation running, that is doing a calculation with the doc\_count of each bucket and the result of the sum agg.

After this calculation I would like to filter (a minimum threshold of that calculated value) and sort based on that calculated bucket script output.

I do not see how I can sort on pipeline bucket outputs, as the documentation explicitely states, that sorting on the terms bucket agg is only for multi bucket aggs.

Maybe I misread the docs and this is somehow possible (or any other alternative that I am not seeing)? This is on Elasticsearch 8.14.

Thanks in advance!

--Alex

---

<div class="post-metadata">

**Author:** ![spinscale](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/spinscale/32/25011_2.png) [@spinscale](https://discuss.elastic.co/u/spinscale)\
**Post date:** [September 3, 2024, 2:35pm UTC](https://discuss.elastic.co/t/pipeline-aggregations-sorting-filtering-after-bucket-script-execution/365786/2 "2024-09-03T14:35:52Z")

</div>

Hey,

quick update, I managed to solve this with ESQL, even though I now have to run a second query before due to not being able to run full text search within ESQL, but keyword only.

It's roughly like this, using the SUM grouped by a field and dividing it.

```auto
FROM idx |
WHERE (term LIKE "a" OR term LIKE "b") |
STATS final_score=SUM(score)/COUNT(field) BY field |
SORT final_score DESC

```

--Alex

P.S. Full text search matching in ESQL wanted 🙂
