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

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