title: Elasticsearch: how to get the top unique values of a field sorted by matching score?
body: <p>I have a collection of addresses. Let's simplify and say the only fields are <code>postcode</code>, <code>city</code>, <code>street</code>, <code>streetnumber</code> and <code>name</code>.
  I'd like to be able to suggest a list of streets when the user enters a postcode, a city and some query for the street.</p>
  
  <p>For example, if the user, in a HTML form, enters:</p>
  
  <pre><code>postcode: 75010
  city: Paris
  street: rue des
  </code></pre>
  
  <p>I'd like to get a list of streets like</p>
  
  <pre><code>'rue des petites écuries'
  'rue des messageries'
  ...
  'rue du faubourg poissonnière'
  ...
  </code></pre>
  
  <p>that I could suggest to the user.</p>
  
  <p>So, I'd like to obtain a list of unique values of the "street" field, sorted according to how well they match my query on the "street" field. I'd like to obtain the 10 best matching streets for this query.</p>
  
  <p>A query returning documents would look like:</p>
  
  <pre><code>{
      "query": {
          "bool": {
              "must": [
                  {{"term": {"postcode": "75010"}},
                  {{"term": {city": "Paris"}},
                  {{"match": {"street": "rue des"}}
              ]    
          }
       }
  }
  </code></pre>
  
  <p>But of course you would get the same street appear many times, since each street can appear multiple times in differerent addresses in the collection.</p>
  
  <p>I tried to use the "aggregation" framework and added an aggs:</p>
  
  <pre><code>{
      "query": {
          "bool": {
              "must": [
                  {{"term": {"postcode": "75010"}},
                      {{"term": {city": "Paris"}},
                      {{"match": {"street": "rue des"}}
              ]    
          }
       },
       "aggs": {
          "street_agg": {
              "terms": {
                  "field": "street",
                  "size": 10
               }
           }           
       }
  }
  </code></pre>
  
  <p>The problem is that it's automatically sorted, not according to the score, but according to the number of documents in each bucket.</p>
  
  <p>I'd like to have the buckets sorted by the score of an arbitrary document picked in each bucket (yes, it's enough to get the score from a single document in a bucket since the score depends only on the content of the street field in my example).</p>
  
  <p>How would you achieve that? </p>