# Get latest records from index

**URL:** <https://discuss.elastic.co/t/get-latest-records-from-index/117035>\
**Category:** Elasticsearch\
**Created:** [January 25, 2018, 11:30am UTC](https://discuss.elastic.co/t/get-latest-records-from-index/117035 "2018-01-25T11:30:47Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Avinash1](https://avatars.discourse-cdn.com/v4/letter/a/f08c70/32.png) [@Avinash1](https://discuss.elastic.co/u/Avinash1)\
**Post date:** [January 25, 2018, 11:30am UTC](https://discuss.elastic.co/t/get-latest-records-from-index/117035/1 "2018-01-25T11:30:47Z")

</div>

Hi ,

In mysql i had query like

select \* from (select idx,machine,customer,FROM\_UNIXTIME(servertime) from Events where customer='MSP\_NH\_TEST' and machine in ('GERMAN','HFN-ENGINE','HFND100035','HFND100036') order by idx desc) as t group by machine;

Which gives me data of all latest records of user.

I tried in EL

{  
"size": 0,  
"query": {  
"match" : {  
"customer" : "BMW\_\_201700051",  
}  
},  
"aggs": {  
"machines": {  
"terms": {  
"field": "machine.keyword",  
"order": {  
"idx": "desc"  
}  
},

```
  }

```

}  
}

But am not getting expected result please someone help me.

---

<div class="post-metadata">

**Author:** ![fdartayre](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/fdartayre/32/27340_2.png) [@fdartayre](https://discuss.elastic.co/u/fdartayre)\
**Post date:** [February 3, 2018, 9:24pm UTC](https://discuss.elastic.co/t/get-latest-records-from-index/117035/2 "2018-02-03T21:24:47Z")

</div>

Hi Avinash,

The simplest way I am thinking of is using [Field Collapsing](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-collapse.html):

```
{
  "query": {
    "match": {
      "customer.keyword": "MSP_NH_TEST"
    }
  },
  "collapse": {
    "field": "machine.keyword"
  },
  "sort": [
    {
      "idx": {
        "order": "desc"
      }
    }
  ]
}

```

Or using nested aggregations this should work as well:

```
{
  "size": 0,
  "query": {
    "match": {
      "customer.keyword": "BMW__201700051"
    }
  },
  "aggs": {
    "machines": {
      "terms": {
        "field": "machine.keyword"
      },
      "aggs": {
        "results": { 
          "top_hits": {
            "sort": [
              {
                "idx": {
                  "order": "desc"
                }
              }
            ],
            "size": 1
          }
        }
      }
    }
  }
}

```

Frédéric

---

<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:** [March 3, 2018, 9:25pm UTC](https://discuss.elastic.co/t/get-latest-records-from-index/117035/3 "2018-03-03T21:25:05Z")

</div>

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