# Return newest document per distinct value field

**URL:** <https://discuss.elastic.co/t/return-newest-document-per-distinct-value-field/32161>\
**Category:** Elasticsearch\
**Created:** [October 14, 2015, 10:52am UTC](https://discuss.elastic.co/t/return-newest-document-per-distinct-value-field/32161 "2015-10-14T10:52:54Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![carlos](https://avatars.discourse-cdn.com/v4/letter/c/ecae2f/32.png) [@carlos](https://discuss.elastic.co/u/carlos)\
**Post date:** [October 14, 2015, 10:52am UTC](https://discuss.elastic.co/t/return-newest-document-per-distinct-value-field/32161/1 "2015-10-14T10:52:54Z")

</div>

Hi,

I have an index composed of the same objects (documents). For simplicity, let's just say each object has three fields:

1. timestamp
2. recordLocator
3. Value

The recordLocator field may be common to several documents. However, the timestamp will be different.

I would like to return the newest document (sorting by timestamp) for each distinct recordLocator. How can this be accomplished?

Carlos

---

<div class="post-metadata">

**Author:** ![carlos](https://avatars.discourse-cdn.com/v4/letter/c/ecae2f/32.png) [@carlos](https://discuss.elastic.co/u/carlos)\
**Post date:** [October 14, 2015, 1:30pm UTC](https://discuss.elastic.co/t/return-newest-document-per-distinct-value-field/32161/2 "2015-10-14T13:30:23Z")

</div>

Hi,

This will do the trick:

aggs \<- '{  
"query": {  
"match\_all": {}  
},  
"aggs": {  
"grouped\_by\_name": {  
"terms": {  
"field": "recordLocator",  
"size": 0  
},  
"aggs": {  
"top\_tag\_hits": {  
"top\_hits": {  
"sort": [  
{  
"timestamp": {  
"order": "desc"  
}  
}  
],  
"size": 1  
}  
}  
}  
}  
}  
}'

I get the feeling it is a bit slow though as it takes about 15 seconds and my index "only" has about 200 million records.

---

<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:44pm UTC](https://discuss.elastic.co/t/return-newest-document-per-distinct-value-field/32161/3 "2017-07-05T23:44:53Z")

</div>


