# Return documents with Aggregations

**URL:** <https://discuss.elastic.co/t/return-documents-with-aggregations/41987>\
**Category:** Elasticsearch\
**Created:** [February 17, 2016, 9:08am UTC](https://discuss.elastic.co/t/return-documents-with-aggregations/41987 "2016-02-17T09:08:23Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![LiorY89](https://avatars.discourse-cdn.com/v4/letter/l/5f9b8f/32.png) [@LiorY89](https://discuss.elastic.co/u/LiorY89)\
**Post date:** [February 17, 2016, 9:08am UTC](https://discuss.elastic.co/t/return-documents-with-aggregations/41987/1 "2016-02-17T09:08:23Z")

</div>

I'm trying to create a query, which will use functions aggregations, such as min, max, avg etc, which will  
return the document itself, or at least its \_id.

for example, when i'm running:

> ```
> "query": {
> "filtered": {
> "filter": {}
> }
> },
> "aggs": {
> "group_by_id": {
> "terms": {
> "field": "EntityId",
> "size": 1000
> },
> "aggs": {
> "max": {
> "max": {
> "field": "timestamp"
> }
> }
> }
> }
> }
> 
> ```

the result is something like:  
"key: -entityID-"  
"doc\_count: "  
"max : { value: 22/11/2015"

I need to return the document which contains the max timestamp, so i need to get the document id.  
i tried to use the top hits, but i can't use functions there...

so is there any valid solution for this issue?

---

<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:** [July 5, 2017, 11:15pm UTC](https://discuss.elastic.co/t/return-documents-with-aggregations/41987/2 "2017-07-05T23:15:47Z")

</div>


