Elastic Search: General and Conditional Filters
I am using Elastic Search, with a match_all query and filtering. In my situation, I want to apply general filter and conditional filters.
Here in pseudo:
- query: match all (works fine)
- filter selection period between d1 and d2 (works fine without bullet 3)
- filter (only applies if the field exists, but how?)
- and etc.
See the following code. I want to apply the "groups" filter only if the "groups" field exists! The filter "exists" does not take effect in this case.
"query":
{
"filtered":
{
"query":
{
"match_all": {}
},
"filter":
{
"bool":
{
"must":
{
"range":
{
"date": {
"from": "2015-06-01",
"to": "2015-06-30"
}
}
},
"must_not":
{
"term":
{
"e.state": 0
}
}
}
},
"filter":
{
"bool":
{
"must":
{
"exists": {"field": "groups"},
"filter":
{
"bool":
{
"must":
{
"term": {"groups.sex": "w"}
},
"should":
{
"terms": {"groups.categories.id": [7,10]}
}
}
}
}
}
}
}
}
}
+3
source to share
1 answer
try it
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"bool": {
"must": [
{
"range": {
"date": {
"from": "2015-06-01",
"to": "2015-06-30"
}
}
},
{
"bool": {
"should": [
{
"missing": {
"field": "groups"
}
},
{
"bool": {
"must": {
"term": {
"groups.sex": "w"
}
},
"should": {
"terms": {"groups.categories.id": [7,10]}
}
}
}
]
}
}
],
"must_not": {
"term": {
"e.state": 0
}
}
}
}
}
}
}
+2
source to share