I am trying to understand how to dynamically build the aggregations with nested and regular filters for regular or nested fields, so, my final query looks like code below and would be fine if it can be simplified to two levels (first – level of filters, second – level of a terms query)
{
"aggs": {
"city": {
"nested": {
"path": "locations"
},
"aggs": {
"city": {
"filter": {
"bool": {
"must": [
{
"terms": {
"locations.country.id": [
"4"
]
}
}
]
}
},
"aggs": {
"city": {
"reverse_nested": {},
"aggs": {
"city": {
"filter": {
"bool": {
"must": [
{
"terms": {
"category.id": [
"24"
]
}
}
]
}
},
"aggs": {
"city": {
"nested": {
"path": "locations"
},
"aggs": {
"city": {
"terms": {
"field": "locations.city.id",
"size": 1000
},
"aggs": {
"source": {
"top_hits": {
"size": 1,
"_source": {
"includes": [
"locations.city.id",
"locations.city.names"
]
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
I am trying to simplify dificult query to Elasticsearch