title: Collapse/Group search query result by a field with supporting sort options
body: <p>I have some documents like the following examples:</p>
  
  <pre><code>{"id": 1, "digest": "A", "date": "2020-05-07"}
  {"id": 2, "digest": "A", "date": "2020-01-07"}
  {"id": 3, "digest": "A", "date": "2020-03-07"}
  {"id": 4, "digest": "B", "date": "2020-01-02"}
  {"id": 5, "digest": "B", "date": "2020-01-01"}
  {"id": 6, "digest": "C", "date": "2020-01-05"}
  </code></pre>
  
  <p>and I want to group the result of the search query by a field (like digest in this example) in the way that:</p>
  
  <ul>
  <li>the result items sort by date descending</li>
  <li>the group leader must be the record which has the minimum date (for example id=2 between 1,2,3 which have the same digest)</li>
  </ul>
  
  <p>in summary, the result that I expected is something like:</p>
  
  <pre><code>[
     {
        "id": 2
        "inner": [{"id": 1}, {"id": 3}],
        "date": "2020-01-07"
     },
     {
        "id": 6
        "inner": [{"id": 6}],
        "date": "2020-01-05"
     },
     {
        "id": 5
        "inner": [{"id": 4}],
        "date": "2020-01-01"
     }
  ]
  </code></pre>
  
  <p>I have tried <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.x/search-request-body.html#request-body-search-collapse" rel="nofollow noreferrer">collapsing fields</a> but by this way, I can't select group leader item and because digest is a hash value, not a static tags, I can't find aggregation method for that.</p>