To obtain list of devices, add terms aggregation on devices as sub-aggregation for username terms aggregation.
Something like this:
GET kibana_sample_data_flights/_search
{
"size":0,
"aggs":{
"city":{
"terms":{
"field": "DestCityName",
"size": 10000
},
"aggs":{
"airports":{
"terms":{
"field": "DestAirportID"
}
},
"nb_airport": {
"cardinality": {
"field": "DestAirportID"
}
},
"nb_airport_filter":{
"bucket_selector":{
"buckets_path":{
"nb_airport": "nb_airport"
},
"script": "params.nb_airport >= 2"
}
},
"sort":{
"bucket_sort": {
"sort": [
{"nb_airport":{"order":"desc"}}
]
}
}
}
}
}
}
You will get:
{
"aggregations" : {
"city" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "London",
"doc_count" : 329,
"nb_airport" : {
"value" : 3
},
"airports" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "LTN",
"doc_count" : 130
},
{
"key" : "LGW",
"doc_count" : 111
},
{
"key" : "LHR",
"doc_count" : 88
}
]
}
},
{
"key" : "Rome",
"doc_count" : 191,
"nb_airport" : {
"value" : 3
},
"airports" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "FCO",
"doc_count" : 89
},
{
"key" : "RM11",
"doc_count" : 70
},
{
"key" : "RM12",
"doc_count" : 32
}
]
}
},......
The result contains DestAirportID for each DestCityName matching the condition of bucket_selector.