# How to use a script field inside Aggregate?

**URL:** <https://discuss.elastic.co/t/how-to-use-a-script-field-inside-aggregate/191190>\
**Category:** Elasticsearch\
**Created:** [July 18, 2019, 11:58am UTC](https://discuss.elastic.co/t/how-to-use-a-script-field-inside-aggregate/191190 "2019-07-18T11:58:00Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![rjernst](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/rjernst/32/6363_2.png) [@rjernst](https://discuss.elastic.co/u/rjernst)\
**Post date:** [July 26, 2019, 5:04pm UTC](https://discuss.elastic.co/t/how-to-use-a-script-field-inside-aggregate/191190/2 "2019-07-26T17:04:49Z")

</div>

Script fields are a feature which produce field values on the fly for the top N documents that match the given query. They are not useable in other parts of the API. In particular, since they are only calculated for top N, it would not be possible to use them for aggregations which operate on every document the query matches.

You will need to duplicate your script inside your sum aggregation. There is a documented example [using a script for a sum aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-sum-aggregation.html#_script_10) which may help. To avoid duplication, you could also [store the script](https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html#modules-scripting-stored-scripts) and reference in both locations by name.

---

_[View the full topic](https://discuss.elastic.co/t/how-to-use-a-script-field-inside-aggregate/191190)._
