Aero Wang
Aero Wang

Reputation: 9267

How to do AND / OR in Filter Aggregation

In https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-filter-aggregation.html we learn:

{
    "aggs" : {
        "t_shirts" : {
            "filter" : { "term": { "type": "t-shirt" } }
        }
    }
}

The above code show how we can aggs for t-shirt, but how do we do:

{
    "aggs" : {
        "t_shirts_or_shorts" : {
            "filter" : { "term": { "type": "t-shirt" } OR "term": { "type": "shorts" } }
        }
    }
}

and

{
    "aggs" : {
        "black_t_shirts" : {
            "filter" : { "term": { "type": "t-shirt" } AND "term": { "color": "black" } }
        }
    }
}

Upvotes: 0

Views: 1321

Answers (2)

jaspreet chahal
jaspreet chahal

Reputation: 9109

You can use "must" and should clause in filter aggregation same as in query.

Query1:

{
  "size": 0, 
  "aggs": {
    "t_shirts": {
      "filter": {
        "bool": {
          "should": [
            {
              "term": {
                "type.keyword": "t-shirt"
              }
            },
            {
              "term": {
                "type.keyword": "shorts"
              }
            }
          ]
        }
      }
    }
  }
}

Query2:

{
  "size": 0, 
  "aggs": {
    "t_shirts": {
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "type.keyword": "t-shirt"
              }
            },
            {
              "term": {
                "color.keyword": "black"
              }
            }
          ]
        }
      }
    }
  }
}

Upvotes: 4

Ahmed Taweel
Ahmed Taweel

Reputation: 41

You can combine filter criteria using the bool tag, much like you can query clauses. You can also check this: Multiple filters and an aggregate in elasticsearch

Upvotes: 0

Related Questions