title: Elasticsearch Nested Filter by Max
body: <p>I have the following documents stored in elasticsearch:</p>
  
  <pre><code>{
    run_number: 3,
    vendor: v_a,
    data: blah
  },
  {
    run_number: 2,
    vendor: v_b,
    data: blah
  },
  {
    run_number: 2,
    vendor: v_b,
    data: blah2
  },
  {
    run_number: 1,
    vendor: v_a,
    data: blah
  },
  {
    run_number: 1,
    vendor: v_b,
    data: blah
  }
  </code></pre>
  
  <p>I am trying to run a search query against this that returns the documents for the most recent run for each vendor. In this example, I want to return the first 3 documents (since they have the max 'run_number' for the given vendor).</p>
  
  <p>My current query is:</p>
  
  <pre><code>{
  "size": 500,
  "aggs": {
      "group_by_vendor": {
          "terms": {
              "field": "vendor"
          },
          "aggs": {
              "max_run_number": {
                  "terms": {
                      "field": "run_number",
                      "order": {"_term": "desc"},
                      "size": 1
                  }
              }
          }
      }
  }
  }
  </code></pre>
  
  <p>But the max_run_number aggregation with size = 1 only limits the nested buckets that are returned. This still returns all hits.</p>