# Trying to find latest time stamp in aggregation

**URL:** <https://discuss.elastic.co/t/trying-to-find-latest-time-stamp-in-aggregation/62415>\
**Category:** Elasticsearch\
**Created:** [October 6, 2016, 5:48pm UTC](https://discuss.elastic.co/t/trying-to-find-latest-time-stamp-in-aggregation/62415 "2016-10-06T17:48:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![BethZ1](https://avatars.discourse-cdn.com/v4/letter/b/eb9ed0/32.png) [@BethZ1](https://discuss.elastic.co/u/BethZ1)\
**Post date:** [October 6, 2016, 5:48pm UTC](https://discuss.elastic.co/t/trying-to-find-latest-time-stamp-in-aggregation/62415/1 "2016-10-06T17:48:48Z")

</div>

I have written a query in elastic search using range on a timestamp field. I need to find the latest timestamp for each group. First I perform the query, then group by the name field, then try to select the latest timestamp by sorting then using top\_hits with size set to 1.

But it is not working, I am seeing multiple names returned with the same timestamp.

Any suggestions are appreciated. Below is my json I use for the search Post query from postman. I am using a bool query because we plan to add more queries, once I get this working.

{  
"query" : {  
"bool": {  
"must": [ {  
"range" : { "timestamp" : { "gte" :"2016-10-05T15:00:35", "lte" : "2016-10-06T15:10:35" } }  
}  
]  
}  
},

"aggs": {  
"groupbyname": {  
"terms": {  
"field": "name"  
},  
"aggs": {  
"top\_group\_hits": {  
"top\_hits": {  
"sort": [  
{  
"timestamp": {  
"order": "desc"  
}  
}  
],  
"size": 1  
}  
}  
}  
}  
}  
}

---

<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, 10:14pm UTC](https://discuss.elastic.co/t/trying-to-find-latest-time-stamp-in-aggregation/62415/2 "2017-07-05T22:14:12Z")

</div>


