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

**URL:** <https://discuss.elastic.co/t/how-to-find-documents-grouped-by-string-field-and-ordered-by-relevance/58213>\
**Category:** Elasticsearch\
**Created:** [August 17, 2016, 6:59am UTC](https://discuss.elastic.co/t/how-to-find-documents-grouped-by-string-field-and-ordered-by-relevance/58213 "2016-08-17T06:59:03Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![un1t](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/un1t/32/5365_2.png) [@un1t](https://discuss.elastic.co/u/un1t)\
**Post date:** [August 17, 2016, 6:59am UTC](https://discuss.elastic.co/t/how-to-find-documents-grouped-by-string-field-and-ordered-by-relevance/58213/1 "2016-08-17T06:59:03Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![mvg](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/mvg/32/98890_2.png) [@mvg](https://discuss.elastic.co/u/mvg)\
**Post date:** [August 17, 2016, 7:19am UTC](https://discuss.elastic.co/t/how-to-find-documents-grouped-by-string-field-and-ordered-by-relevance/58213/2 "2016-08-17T07:19:13Z")

</div>

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:

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

```

---

<div class="post-metadata">

**Author:** ![un1t](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/un1t/32/5365_2.png) [@un1t](https://discuss.elastic.co/u/un1t)\
**Post date:** [August 17, 2016, 10:59am UTC](https://discuss.elastic.co/t/how-to-find-documents-grouped-by-string-field-and-ordered-by-relevance/58213/3 "2016-08-17T10:59:56Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 5, 2017, 10:27pm UTC](https://discuss.elastic.co/t/how-to-find-documents-grouped-by-string-field-and-ordered-by-relevance/58213/4 "2017-07-05T22:27:15Z")

</div>


