A nested bool search query with must and should statements
I am trying to insert an aggregation and apply a filter to it.
See the following example:
Car
- the brand
- name
- Features:
Functions
- name
- value
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 is the request:
"query": {
"nested": {
"path": "features",
"query": {
"bool": {
"should": [
{
"match": {
"features.color": "blue"
}
},
{
"match": {
"features.color": "white"
}
}
],
"must": [
{"match": {
"features.power": 150
}}
]
}
}
}
}
Query result: A, B, C, F
The expected output should be B, C, F (color = blue OR color = white) AND wattage = 150
source to share
Try this query:
"query": {
"nested": {
"path": "features",
"query": {
"bool": {
"should": [
{
"match": {
"features.color": "blue"
}
},
{
"match": {
"features.color": "white"
}
}
],
"must": [
{"match": {
"features.power": 150
}}
]
}
}
}
}
Value, the fields you use in the request must be prefixed with the name path
: features.color
, features.power
.
EDIT
Try this query (I missed the essential here - you need two must
s, one bool
with should
s):
{
"query": {
"nested": {
"path": "features",
"query": {
"bool": {
"must": [
{
"match": {
"features.power": 150
}
},
{
"bool": {
"should": [
{
"match": {
"features.color": "blue"
}
},
{
"match": {
"features.color": "white"
}
}
]
}
}
]
}
}
}
}
}
source to share