title: How to get latest values for each group with an Elasticsearch query?
body: <p>I have some documents indexed on Elasticsearch, looking like these samples:</p>
  
  <pre><code>{'country': 'France', 'collected': '2015-03-12', 'value': 20}
  {'country': 'Canada', 'collected': '2015-03-12', 'value': 21}
  {'country': 'Brazil', 'collected': '2015-03-12', 'value': 33}
  {'country': 'France', 'collected': '2015-02-01', 'value': 10}
  {'country': 'Canada', 'collected': '2015-02-01', 'value': 11}
  {'country': 'Mexico', 'collected': '2015-02-01', 'value': 9}
  ...
  </code></pre>
  
  <p>I want to build a query that gets one result per country, getting only the ones with <code>max(collected)</code>.</p>
  
  <p>So, for the examples shown above, the results would be something like:</p>
  
  <pre><code>{'country': 'France', 'collected': '2015-03-12', 'value': 20}
  {'country': 'Canada', 'collected': '2015-03-12', 'value': 21}
  {'country': 'Brazil', 'collected': '2015-03-12', 'value': 33}
  {'country': 'Mexico', 'collected': '2015-02-01', 'value': 9}
  </code></pre>
  
  <p>I realized I need to do aggregation on <code>country</code>, but I'm failing to understand how to limit the results on <code>max(collected)</code>.</p>
  
  <p>Any ideas?</p>