In my elasticsearch index "people" there are the following documents:
{"name": "John", "district": 1},
{"name": "Anne", "district": 1},
{"name": "Mary", "district": 2},
{"name": "Bobby", "district": 2},
{"name": "Nick", "district": 1},
{"name": "Bob", "district": 3},
{"name": "Kenny", "district": 1}
I would like to get a result of documents that have a district of 2 or 1, but only 2 of them maximum. So if the above were my whole index, I would want it to return:
{"name": "John", "district": 1},
{"name": "Anne", "district": 1},
{"name": "Mary", "district": 2},
{"name": "Bobby", "district": 2},
Is it possible to achieve this with a single query in elastic? Thank you very much for your help!
Something like this should do it:
GET /some_index/some_type/_search?search_type=count
{
"aggs": {
"district_1_or_2": {
"filter": {
"bool": {
"should": [
{
"term": {
"district": 1
}
},
{
"term": {
"district": 2
}
}
]
}
},
"aggs": {
"district": {
"terms": {
"field": "district",
"size": 10
},
"aggs": {
"top": {
"top_hits": {
"size": 2
}
}
}
}
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With