If you want the unique values of the numbers, you can use this:
DELETE test
POST test/_doc
{ "type": "a", "number": 15 }
POST test/_doc
{ "type": "a", "number": 15 }
POST test/_doc
{ "type": "b", "number": 56 }
POST test/_doc
{ "type": "a", "number": 40 }
POST test/_doc
{ "type": "b", "number": 2 }
GET test/_search
{
"size": 0,
"aggs": {
"by_type": {
"terms": {
"field": "type.keyword"
},
"aggs": {
"by_number": {
"terms": {
"field": "number"
}
}
}
}
}
}
This gives:
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 5,
"relation": "eq"
},
"max_score": null,
"hits": []
},
"aggregations": {
"by_type": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "a",
"doc_count": 3,
"by_number": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": 15,
"doc_count": 2
},
{
"key": 40,
"doc_count": 1
}
]
}
},
{
"key": "b",
"doc_count": 2,
"by_number": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": 2,
"doc_count": 1
},
{
"key": 56,
"doc_count": 1
}
]
}
}
]
}
}
}
But if you want to get all the values, even though some of them are already collected, you could do that instead:
GET test/_search?filter_path=aggregations.by_type.buckets.key,aggregations.by_type.buckets.all_numbers.hits.hits.fields.number
{
"size": 0,
"aggs": {
"by_type": {
"terms": {
"field": "type.keyword"
},
"aggs": {
"all_numbers": {
"top_hits": {
"size": 1000,
"docvalue_fields": ["number"],
"_source": false
}
}
}
}
}
}
{
"aggregations": {
"by_type": {
"buckets": [
{
"key": "a",
"all_numbers": {
"hits": {
"hits": [
{
"fields": {
"number": [
15
]
}
},
{
"fields": {
"number": [
15
]
}
},
{
"fields": {
"number": [
40
]
}
}
]
}
}
},
{
"key": "b",
"all_numbers": {
"hits": {
"hits": [
{
"fields": {
"number": [
56
]
}
},
{
"fields": {
"number": [
2
]
}
}
]
}
}
}
]
}
}
}