Leandro Castro
Leandro Castro

Reputation: 558

simple group by in elastic search

This is my search:

{
 "query": {
   "filtered": { 
     "filter": {
       "term": { "cityId": "10777"}
     },
     "query" : {
        "query_string": {
          "query": "pizza",
          "fields": ["name", "main", "category.name"]
        }
      }
   }
 },
 "sort": [
        { "premium":   { "order": "desc" } }
    ]
}

This works perfectly. He brings me several categories, and I would like to group by them. example: Group by category "pizzerias"

Upvotes: 0

Views: 396

Answers (1)

Val
Val

Reputation: 217554

All you have to do is to add a terms aggregation to the mix and you're done.

Supposing your category field is the category.name one, you can do it like this.

{
  "query": {
    "filtered": {
      "filter": {
        "term": {
          "cityId": "10777"
        }
      },
      "query": {
        "query_string": {
          "query": "pizza",
          "fields": [
            "name",
            "main",
            "category.name"
          ]
        }
      }
    }
  },
  "sort": [
    {
      "premium": {
        "order": "desc"
      }
    }
  ],
  "aggs": {
    "categories": {
      "terms": {
        "field": "category.name"
      }
    }
  }
}

Upvotes: 2

Related Questions