Sort Date for different value of particular field in Single Query

Lets say I have following content on index.

{ date : 2019-01-21T08:20:18.962Z , student : "A", "City": "city1" }
{ date : 2019-01-21T08:20:55.962Z , student : "A", "City": "city1" }
{ date : 2019-01-21T08:29:20.962Z , student : "B", "City": "city1" }
{ date : 2019-01-21T08:20:10.962Z , student : "A", "City": "city1" }
{ date : 2019-01-21T08:29:21.962Z , student : "B", "City": "city1" }

I want to get the latest date for student A and Student B in single query so that I will get following output :
{ date : 2019-01-21T08:**20:55.**962Z , student : "A", "City": "city1" }
{ date : 2019-01-21T08:29:21.962Z , student : "B", "City": "city1" }

I know using sorting on date desc and applying must match on student : "A" will get me latest date for student A , and like wise for student B. But I need to run two separate query for this.

Please let know if we can achieve this in single query and how .

Thanks .

Have a look at the TopHits aggregation.

Ensure that the student field is mapped as keyword for use with aggegations.

{
  "size": 0,
  "aggs": {
    "students": {
      "terms": {
        "field": "student",
        "size": 100
      },
      "aggs": {
        "top": {
          "top_hits": {
            "sort": [
              {
                "date": {
                  "order": "desc"
                }
              }
            ],
            "size": 1
          }
        }
      }
    }
  }
}

Thanks . It worked for me.

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