title: Query or Filter for minimum field value?
body: <p>Example: a document stored in an index represents test scores and meta data about each test. </p>
  
  <pre><code>{ "test": 1, "user":1, "score":100, "meta":"other data" },
  { "test": 2, "user":2, "score":65, "meta":"other data" },
  { "test": 3, "user":2, "score":88, "meta":"other data" },
  { "test": 4, "user":1, "score":23, "meta":"other data" }
  </code></pre>
  
  <p>I need to be able to filter out all but the lowest test score and return the associated metadata with that test for each test taker. So my expected result set would be:</p>
  
  <pre><code>{ "test": 2, "user":2, "score":65, "meta":"other data" },
  { "test": 4, "user":1, "score":23, "meta":"other data" }
  </code></pre>
  
  <p>The only way I see to do this now is by first doing a terms aggregation by user with a nested min aggregation to get their lowest score. </p>
  
  <pre><code>POST user/tests/_search
  {
    "aggs" : {
      "users" : {
        "terms" : {
            "field" : "user",
            "order" : { "lowest_score" : "asc" }
        },
        "aggs" : {
          "lowest_score" : { "min" : { "field" : "score" } }
        }
      }
    },"size":0
  }
  </code></pre>
  
  <p>Then I'd have to take the results of that query and do a filtered query for EACH user and filter on the lowest score value to grab the rest of the metadata. Yuk.</p>
  
  <pre><code>POST user/tests/_search
  {
    "query": {
      "filtered": {
        "filter": {
          "bool": {
            "must": [
              {"term": { "user": {"value": "1" }}},
              {"term": { "score": {"value": "22" }}}
            ]
          }
        }
      }
    }
  }
  </code></pre>
  
  <p>I'd like to know if there is a way to return return one response that has the lowest test score for each test taker and includes the original _source document. </p>
  
  <p>Solutions?</p>
  
  <h1>UPDATE - SOLVED</h1>
  
  <p>The following gives me the lowest score document for each user and is ordered by the overall lowest score. And, it includes the original document.</p>
  
  <pre><code>GET user/tests/_search?search_type=count
  {
    "aggs": {
      "users": {
        "terms": {
          "field": "user",
          "order" : { "lowest_score" : "asc" }
        },
        "aggs": {
          "lowest_score": { "min": { "field": "score" }},
          "lowest_score_top_hits": {
            "top_hits": {
              "size":1,
              "sort": [{"score": {"order": "asc"}}]
            }
          }
        }
      }
    }
  }
  </code></pre>