How to group docs by latest doc and run aggregation on the group in elastic search?

Hi ,

I need to get all clients under a partnerId & since there would be many clients I need to group the clients by clientId,latest reportDate and run some aggregations .

Index data is like below -

[
    {  partnerId: "PID1234", clientId: "c1234", reportDate: "2022-02-01"   },
    {  partnerId: "PID1234", clientId: "c1234", reportDate: "2030-02-01"   },
    {  partnerId: "PID1111", clientId: "c1222", reportDate: "2010-02-01"   },
    {  partnerId: "PID2222", clientId: "c1444", reportDate: "2013-02-01"   },
 ]

I need to do something like the below query, the problem is top hits don't accept sub aggregations -

{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "partnerId": "PID1234"
          }
        }
      ]
    }
  },
  "aggs": {
    "groupp": {
      "top_hits": {
        "sort": [
          {
            "clientId": {
              "order": "desc"
            }
          }
        ],
        "size": 1,
        "aggs": {
            "total_engagement_count": {
              "sum": { "field": "recommendations.totalEngagement" }
            }
          }
      }
    }
  }
}

Hi!!
Look this:

It’s a fairly common requirement to do analysis only on the last known state of an entity.
See here for solutions.

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