# Aggregation using something similar to First when data is grouped

**URL:** <https://discuss.elastic.co/t/aggregation-using-something-similar-to-first-when-data-is-grouped/244587>\
**Category:** Elasticsearch\
**Created:** [August 11, 2020, 3:47pm UTC](https://discuss.elastic.co/t/aggregation-using-something-similar-to-first-when-data-is-grouped/244587 "2020-08-11T15:47:51Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Raster](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/raster/32/47522_2.png) [@Raster](https://discuss.elastic.co/u/Raster)\
**Post date:** [August 11, 2020, 3:47pm UTC](https://discuss.elastic.co/t/aggregation-using-something-similar-to-first-when-data-is-grouped/244587/1 "2020-08-11T15:47:51Z")

</div>

Lets say I have data like this. Every unique "key" has a unique "long key" - totally 1 to 1.  
Because key is numeric will prefer using it for agrregating (using) using terms-\> field.  
Field "somedata" is subject to aggregations like sum etc when grouped by the key.  
When aggregating for sum or avg of somedata- would like to also compute long key-  
  
**Source Data::**

| key | long key | somedata |
| 1 | XYZ | 10 |
| 1 | XYZ | 20 |
| 1 | XYZ | 20 |
| 2 | PQR | 30 |
| 2 | PQR | 35 |

Anything like first() or most() exists to show results as below. Main concern is how to capture longkey as shown below in a sample aggregation?  
**Expected Aggregation representation:**

| key | long key | sum of somedata |
| 1 | XYZ | 50 |
| 2 | PQR | 65 |

R

---

<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 12, 2020, 9:29am UTC](https://discuss.elastic.co/t/aggregation-using-something-similar-to-first-when-data-is-grouped/244587/2 "2020-08-12T09:29:45Z")

</div>

You could have another `top_hits` aggregation within the `terms` agg that returns the two fields which then could be extracted. See [https://www.elastic.co/guide/en/elasticsearch/reference/7.8/search-aggregations-metrics-top-hits-aggregation.html](https://www.elastic.co/guide/en/elasticsearch/reference/7.8/search-aggregations-metrics-top-hits-aggregation.html)

---

<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:** [September 9, 2020, 9:29am UTC](https://discuss.elastic.co/t/aggregation-using-something-similar-to-first-when-data-is-grouped/244587/3 "2020-09-09T09:29:48Z")

</div>

Closed on September 9, 2020, 9:29am UTC

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