# Painless Script on Top Hit of Average Aggregation

**URL:** <https://discuss.elastic.co/t/painless-script-on-top-hit-of-average-aggregation/181849>\
**Category:** Elasticsearch\
**Tags:** painless\
**Created:** [May 20, 2019, 2:17pm UTC](https://discuss.elastic.co/t/painless-script-on-top-hit-of-average-aggregation/181849 "2019-05-20T14:17:11Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![6tUBp3gwd9Zp](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/6tubp3gwd9zp/32/45240_2.png) [@6tUBp3gwd9Zp](https://discuss.elastic.co/u/6tUBp3gwd9Zp)\
**Post date:** [May 20, 2019, 2:17pm UTC](https://discuss.elastic.co/t/painless-script-on-top-hit-of-average-aggregation/181849/1 "2019-05-20T14:17:12Z")

</div>

I want to do some scripting on a top hit average aggregation. (I think the images are pretty much self-explanatory. Script is just an example). But when I do so I get an "Internal Server Error". What am I doing wrong?

![1](https://us1.discourse-cdn.com/elastic/original/3X/0/1/015cf81fb45336cf5b4c445ac373d1925ce0b094.png)

![2](https://us1.discourse-cdn.com/elastic/original/3X/e/0/e0e4c3603a57810c51520cdfc3b6fd1a282a10ff.png)

---

<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 20, 2019, 2:59pm UTC](https://discuss.elastic.co/t/painless-script-on-top-hit-of-average-aggregation/181849/2 "2019-05-20T14:59:11Z")

</div>

> [@6tUBp3gwd9Zp](#):
>
> I think the images are pretty much self-explanatory

I'm not sure what this is trying to achieve. You're using the top\_hits agg to get only the top 1 document (sorted by time, so "latest") and computing an average of that single value (so presumably min or max would work equally well here?).

The `advanced` panel is where you can merge arbitrary JSON into the request which is where I see you're trying to retrieve a value using a script but this is going wrong. Have you tried debugging the JSON you're trying to merge with by checking out the `Inspect->View:Requests` menu options in Kibana? Another option may be to create a "scripted field" in your index pattern. Either way, this is likely more a question for the Kibana forum.

---

<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 17, 2019, 2:59pm UTC](https://discuss.elastic.co/t/painless-script-on-top-hit-of-average-aggregation/181849/3 "2019-06-17T14:59:12Z")

</div>

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