# Sorting by timestamp

**URL:** <https://discuss.elastic.co/t/sorting-by-timestamp/49496>\
**Category:** Elasticsearch\
**Created:** [May 8, 2016, 8:07pm UTC](https://discuss.elastic.co/t/sorting-by-timestamp/49496 "2016-05-08T20:07:14Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![maher](https://avatars.discourse-cdn.com/v4/letter/m/a6a055/32.png) [@maher](https://discuss.elastic.co/u/maher)\
**Post date:** [May 8, 2016, 8:07pm UTC](https://discuss.elastic.co/t/sorting-by-timestamp/49496/1 "2016-05-08T20:07:14Z")

</div>

Hi,  
I am trying to get the last 3 consulted products :  
so i need to make an aggregation based on productcode then use the option order .  
here is what i am trying to do

```
{
"size" : 0,
"aggs" : {
    "products" : {
        "terms" : {
          "field" : "productcode",
          "order": {
            "timestamp" : "asc" 
          },
          "size" : 3
        }
    }
}
 }

```

this won't work for sure, but is there any solution for this problem?? any proposition will be helpful

Thank you!

---

<div class="post-metadata">

**Author:** ![maher](https://avatars.discourse-cdn.com/v4/letter/m/a6a055/32.png) [@maher](https://discuss.elastic.co/u/maher)\
**Post date:** [May 9, 2016, 9:06am UTC](https://discuss.elastic.co/t/sorting-by-timestamp/49496/2 "2016-05-09T09:06:51Z")

</div>

I Found a solution for this problem:

{  
"aggs": {  
"products": {  
"terms": {  
"field": "code",  
"order":{"first\_hit":"desc"},  
"size" : 3  
},  
"aggs": {  
"first\_hit": {  
"max": {  
"field" : "@timestamp"  
}  
}  
}  
}  
}  
}

I hope this will help someone 😃

---

<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:53pm UTC](https://discuss.elastic.co/t/sorting-by-timestamp/49496/3 "2017-07-05T22:53:04Z")

</div>


