Groupby and get latest element

I have a client app that is sending json to an opensearch instance. Here’s the mapping that I am using:

...
  "mappings": {
    "properties": {
      "@timestamp":  {
        "type" : "date", "format" : "yyyy-MM-dd HH:mm:ss.SSSSSSSSS"
        },
      "ItemStatusEvent":  {
        "properties": {
            "itemId" : {"type" : "keyword"},
            "itemStatus" : {"type" : "keyword"}
            }
        },
...

As you can see there can be several ItemStatusEvent for the same itemId over the time. I would like to create a Pie Chart using something like:

piechart

How should I modify my query in order to take the latest ItemStatusEvent per itemId ?

Any help will be greatly appreciated :slight_smile:

Jean-Pierre