Zirc75
Zirc75

Reputation: 407

Nested search bool query with must and should operators

I'm trying a nested aggregation and to apply a filter on it.

See the following example:

Car

Features

Here's some test data:

car_A:
{
 brand :"VW",
 name: "Golf",
 features: [
  {name: "color", value: "black"},
  {name: "power", value: "150"}
 ]
}

car_B:
{
 brand :"VW",
 name: "Golf",
 features: [
  {name: "color", value: "blue"},
  {name: "power", value: "150"}
 ]
}

car_C:
{
 brand :"VW",
 name: "Golf",
 features: [
  {name: "color", value: "white"},
  {name: "power", value: "150"}
 ]
}

car_D:
{
 brand :"BMW",
 name: "X3",
 features: [
  {name: "color", value: "white"},
  {name: "power", value: "180"}
 ]
}

car_E:
{
 brand :"BMW",
 name: "X5",
 features: [
  {name: "color", value: "blue"},
  {name: "power", value: "250"}
 ]
}

car_F:
{
 brand :"BMW",
 name: "X3",
 features: [
  {name: "color", value: "blue"},
  {name: "power", value: "150"}
 ]
}

and here's the query:

"query": {
"nested": {
  "path": "features",
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "features.color": "blue"
          }
        },
        {
          "match": {
            "features.color": "white"
          }
        }
      ],
      "must": [
        {"match": {
          "features.power": 150
        }}
      ]
    }
  }
 }
} 

The query result is A,B,C,F

The expected result should be B,C,F (color=blue OR color=white) AND power=150

Upvotes: 3

Views: 2509

Answers (1)

Andrei Stefan
Andrei Stefan

Reputation: 52368

Try this query:

"query": {
"nested": {
  "path": "features",
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "features.color": "blue"
          }
        },
        {
          "match": {
            "features.color": "white"
          }
        }
      ],
      "must": [
        {"match": {
          "features.power": 150
        }}
      ]
    }
  }
 }
} 

Meaning, the fields that you use in the query should be prefixed with the name of the path: features.color, features.power.

EDIT:

Try this query (I missed the essential here - you need two musts, one being a bool with shoulds):

{
  "query": {
    "nested": {
      "path": "features",
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "features.power": 150
              }
            },
            {
              "bool": {
                "should": [
                  {
                    "match": {
                      "features.color": "blue"
                    }
                  },
                  {
                    "match": {
                      "features.color": "white"
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }
  }
}

Upvotes: 2

Related Questions