# ES Query to sort data on Timestamp

**URL:** <https://discuss.elastic.co/t/es-query-to-sort-data-on-timestamp/78394>\
**Category:** Elasticsearch\
**Created:** [March 13, 2017, 5:50pm UTC](https://discuss.elastic.co/t/es-query-to-sort-data-on-timestamp/78394 "2017-03-13T17:50:39Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![saggarsunil](https://avatars.discourse-cdn.com/v4/letter/s/9fc348/32.png) [@saggarsunil](https://discuss.elastic.co/u/saggarsunil)\
**Post date:** [March 13, 2017, 5:50pm UTC](https://discuss.elastic.co/t/es-query-to-sort-data-on-timestamp/78394/1 "2017-03-13T17:50:39Z")

</div>

I have a very basic requirement. I am indexing the records based on timestamp.

E.g

{ "temperature": [value], "deviceID":[value] , Timestamp: [ts]}  
{ "temperature": [value], "deviceID":[value],Timestamp: [ts] }  
{ "temperature": [value], "deviceID":[value],Timestamp: [ts] }

These record/events are added every 1 minute. I would like to query ES and find out the last 10 records ordered by timestamp for a particular deviceID. So, the first record should be t-10, then t-9, then t-8, ...

```
{

"sort":[{"Timestamp": { "order" : "asc" }}],
  "query": {
    "bool": {
      "must": {
        "match": {
          "deviceID": 1
        }
      },
      "filter": {
        "range": {
          "Timestamp": {
            "gte": "now-10m"
          }
        }
      }
    }
},
"_source" : ["temperature","deviceID","Timestamp"]
}

```

I realized that every time it gives different results ... ( though it is sorted based on Timestamp ). It is not giving any definitive result if i run it multiple time.

Am i missing something obvious ?

Please advise as i am not an expert in ES query DSL.`Preformatted text`

---

<div class="post-metadata">

**Author:** ![spinscale](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/spinscale/32/25011_2.png) [@spinscale](https://discuss.elastic.co/u/spinscale)\
**Post date:** [March 13, 2017, 8:00pm UTC](https://discuss.elastic.co/t/es-query-to-sort-data-on-timestamp/78394/2 "2017-03-13T20:00:47Z")

</div>

Hey,

can you be more specific in what way the results are diverting? Do you have results with the same timestamp and thus the sorting is not stable?

--Alex

---

<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:** [April 10, 2017, 8:01pm UTC](https://discuss.elastic.co/t/es-query-to-sort-data-on-timestamp/78394/3 "2017-04-10T20:01:25Z")

</div>

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