# Find earliest document per id

**URL:** <https://discuss.elastic.co/t/find-earliest-document-per-id/210546>\
**Category:** Elasticsearch\
**Created:** [December 4, 2019, 1:46pm UTC](https://discuss.elastic.co/t/find-earliest-document-per-id/210546 "2019-12-04T13:46:27Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ngruson](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/ngruson/32/98978_2.png) [@ngruson](https://discuss.elastic.co/u/ngruson)\
**Post date:** [December 4, 2019, 1:46pm UTC](https://discuss.elastic.co/t/find-earliest-document-per-id/210546/1 "2019-12-04T13:46:27Z")

</div>

I have an index in Elasticsearch which contains multiple documents per ID.  
For the 50 most recent IDs, I'd like to select the first document based on the timestamp.  
Is such a thing possible with Elasticsearch?

For example, several documents with the fields ID and Timestamp:  
ID, Timestamp  
**1, 16:00**  
1, 16:05  
1, 16:10  
**2, 17:00**  
2, 17:10  
2, 17:20

Cheers,  
Nils

---

<div class="post-metadata">

**Author:** ![abdon](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/abdon/32/9195_2.png) [@abdon](https://discuss.elastic.co/u/abdon)\
**Post date:** [December 4, 2019, 1:50pm UTC](https://discuss.elastic.co/t/find-earliest-document-per-id/210546/2 "2019-12-04T13:50:01Z")

</div>

You can use [field collapsing](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html#request-body-search-collapse) for that. You'd sort on the timestamp, and collapse on the ID.

---

<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:** [January 1, 2020, 1:50pm UTC](https://discuss.elastic.co/t/find-earliest-document-per-id/210546/3 "2020-01-01T13:50:22Z")

</div>

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