How to find documents grouped by string field and ordered by relevance?

In SQL it would be something like this:
select name from products where shop_id=1 and name like 'banana%' group by name;

In Elasticsearch this can be achieved using aggregations. You can use the terms aggregation to group your documents by a particular field and then use the top_hits aggregation to get the hits for each of the groups.

Example request:

curl -XGET "http://localhost:9200/_search" -d'
{
  "query" : {
     // your query
  },
  "aggs": {
    "group-by": {
      "terms": {
        "field": "my-field"
      },
      "aggs": {
        "grouped-documents": {
          "top_hits": {
            "size": 10
          }
        }
      }
    }
  }
}' 
1 Like

Thank you.

First time I tried it, I did not realize, that in this case I need custom analyzer with keyword tokenizer and lowercase filter.

"analyzer": {
    "lower_keyword": {
        "type": "custom",
        "tokenizer": "keyword",
        "filter": "lowercase",
    },
},

With this analyzer it works.