title: Elasticsearch: Aggregate only over the n most relevant search results
body: <p>I want to run an aggregation over a very small subset of documents. The subset should comprise only those documents whose domCompleteTime field value matches, or closely matches a supplied value.</p>
  
  <p>The closest I've got is aggregating over documents matching a narrow range (see below) but the query is not dependable because the number of document hits can range from zero to 100+. </p>
  
  <p>What I really want is to rewrite the query to always aggregate over the 5 closest matches. The closest I've found in the es docs is <code>top_hits</code> but AFAICT that seems to only work over groups, which is not what I'm looking for here.</p>
  
  <pre><code>{
    "query": {
      "filtered": {
        "filter": {
          "bool": {
            "must": [
              {
                "script": {
                  "script": {
                    "params": {
                      "matchValue": "32562"
                    },
                    "inline": "(Math.abs(matchValue - doc['domCompleteTime'].value) &lt; (matchValue/1000))"
                  }
                }
              }
            ]
          }
        }
      }
    },
    "aggs": {
      "domParseEnd": {
        "percentiles": {
          "field": "domParseEnd",
          "percents": [50]
        }
      }
    }
  }
  </code></pre>