# Get latest document of each unique record

**URL:** https://discuss.elastic.co/t/get-latest-document-of-each-unique-record/52356
**Category:** Elasticsearch
**Created:** [June 9, 2016, 4:52pm UTC](https://discuss.elastic.co/t/get-latest-document-of-each-unique-record/52356 "2016-06-09T16:52:38Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![esap](https://avatars.discourse-cdn.com/v4/letter/e/7c8e57/32.png) [@esap](https://discuss.elastic.co/u/esap)
#### Post date: [June 9, 2016, 4:52pm UTC](https://discuss.elastic.co/t/get-latest-document-of-each-unique-record/52356/1 "2016-06-09T16:52:38Z")

</div>

We have about 300,000 unique customers. We have one document each for every order placed, so we have several million order documents since the past 3 years.

How can I get the latest order document for each unique customer's record?

{  
"\_id" : 1,  
"customer\_id" : 1001,  
"order\_amount" : 15.00,  
"timestamp" : 1/1/2014,  
},  
{  
"\_id" : 2,  
"customer\_id" : 1001,  
"order\_amount" : 17.00,  
"timestamp" : 1/1/2015,  
},  
{  
"\_id" : 3,  
"customer\_id" : 1002,  
"order\_amount" : 13.00,  
"timestamp" : 1/1/2016,  
}

I need the output to be records \_id - 2 and 3. Is this possible at all?

---

<div class="post-metadata">

### Author: ![mikemccand](https://avatars.discourse-cdn.com/v4/letter/m/f04885/32.png) [@mikemccand](https://discuss.elastic.co/u/mikemccand)
#### Post date: [June 9, 2016, 8:18pm UTC](https://discuss.elastic.co/t/get-latest-document-of-each-unique-record/52356/2 "2016-06-09T20:18:46Z")

</div>

Maybe parent/child? Index one parent document for each customer, and a child document for each order that customer has? But then I'm unsure at query time how to only retrieve e.g. the top 2 children per parent ... maybe using top hits aggregation, sorting by timestamp descending, keeping the top 2.

Mike McCandless

---

<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:44pm UTC](https://discuss.elastic.co/t/get-latest-document-of-each-unique-record/52356/3 "2017-07-05T22:44:55Z")

</div>


