title: Elasticsearch: How to return all documents that have the highest value in a field?
body: <p>I'm quite a newbie to Elasticsearch, and I'm currently having some difficulty with a rather basic problem. Suppose I have the following mapping:</p>
  
  <pre><code>PUT /myindex/_mappings/people 
  {
      "properties": {
          "name": {"type": "keyword"},
          "age" : {"type": "integer"},
      }
  }
  </code></pre>
  
  <p>with the following documents:</p>
  
  <pre><code>{"name": "Bob", "age": 20},
  {"name": "Ben", "age": 25},
  {"name": "Eli", "age": 30},
  {"name": "Eva", "age": 20},
  {"name": "Jan", "age": 21},
  {"name": "Jim", "age": 20},
  {"name": "Lea", "age": 30},
  </code></pre>
  
  <p>How do I create a single query which returns all people that are the oldest in the index? In other words, I'm expecting Eli and Lea to be returned because they are both 30 years of age, older than everyone else. </p>
  
  <p>I'm using Elasticsearch API 6.0.0 for javascript (my application is written in nodejs). Right now, my workaround is to perform 2 requests to the database. The first is to aggregate the max age (which should return 30), and then use this max age to perform another request: </p>
  
  <pre><code>GET /myindex/people/_search
  {
      "aggs": {
          "max_age": {"max": {"field": "age"}}
      }
  }
  
  GET /myindex/people/_search
  {
      "query": {"term": {"age": &lt;max_age&gt;}} // where &lt;max_age&gt; should be 30
  }
  </code></pre>
  
  <p>Obviously, this is very inefficient. Can you help me formulate a single query that does all of this?</p>
  
  <p>The difficult thing is I don't know beforehand how many documents that have the highest value, which means I can't use the "size" approach mentioned here "<a href="https://stackoverflow.com/questions/23733728/single-query-to-find-document-with-largest-value-for-some-field">Single query to find document with largest value for some field</a>"</p>
  
  <p>Thanks in advance!</p>