3
votes

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
Ok. And why the query you have doesn't work? - Andrei Stefan
And when you copy-pasted your query, you probably wanted to leave something out but you forgot to add a curly brace for the bool statement. Or this is your error in the query. - Andrei Stefan
I got this error : { "error": { "root_cause": [ { "type": "parsing_exception", "reason": "[match] malformed query, expected [END_OBJECT] but found [FIELD_NAME]", "line": 19, "col": 11 } ], "type": "parsing_exception", "reason": "[match] malformed query, expected [END_OBJECT] but found [FIELD_NAME]", "line": 19, "col": 11 }, "status": 400 } - Pierre Jones
If I put my bool / should inside curly braces It returns a "Bad String" error (I use Kibana to test my queries) - Pierre Jones

1 Answers

6
votes

This works for me:

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