Combine must and should

2019-07-27 12:45发布

问题:

I've some troubles with an elasticsearch query. (I use elasticsearch 5). I want to combine must bool query and should in order to create a query which match this condition :

Get users which match (city = x) AND (school = y) AND (age = 12) AND (team = a OR b)

I tried many queries but I still have a query malformed exception.

{
  "query": {
    "bool": {
      "must" : [
        {
          "match": {
            "city": "x"
          }
        },
        {
          "match" : {
            "school" : "y"
        }
        },
        {
          "match" : {
            "age" : 12
        },
          "bool": {
            "should": [
              {"term": {"team": "A"}},
              {"term": {"team": "B"}}
            ]
          }
        }
      ]
    }
  }
}

I hope someone could help me :D

Thanks for your help

回答1:

This works for me:

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "city": "x"
          }
        },
        {
          "match": {
            "school": "y"
          }
        },
        {
          "match": {
            "age": 12
          }
        },
        {
          "bool": {
            "should": [
              {
                "term": {
                  "team": "A"
                }
              },
              {
                "term": {
                  "team": "B"
                }
              }
            ]
          }
        }
      ]
    }
  }
}