Skip to content

Instantly share code, notes, and snippets.

@djptek
Created January 17, 2020 15:04
Show Gist options
  • Save djptek/0b2cfa5a44a08ba2926fecb0a9c6cced to your computer and use it in GitHub Desktop.
Save djptek/0b2cfa5a44a08ba2926fecb0a9c6cced to your computer and use it in GitHub Desktop.
mean of a value per bucket where bucket may have multiple children
PUT test/_doc/01_01
{
"parent_id": "01",
"value": 10
}
PUT test/_doc/01_02
{
"parent_id": "01",
"value": 10
}
PUT test/_doc/01_03
{
"parent_id": "01",
"value": 10
}
PUT test/_doc/02_01
{
"parent_id": "02",
"value": 20
}
# not what we want
GET test/_search
{
"size": 0,
"aggs": {
"mean_of_three_documents": {
"avg": {
"field": "value"
}
}
}
}
# I think this is what we want
GET test/_search
{
"size": 0,
"aggs": {
"all_parent_ids": {
"terms": {
"field": "parent_id.keyword"
},
"aggs": {
"value_per_parent": {
"max": {
"field": "value"
}
}
}
},
"average_parent_value": {
"avg_bucket": {
"buckets_path": "all_parent_ids>value_per_parent"
}
}
}
}
GET test/_search
{
"aggs": {
"4": {
"avg_bucket": {
"buckets_path": "4-bucket>4-metric"
}
},
"4-bucket": {
"terms": {
"field": "parent_id.keyword",
"order": {
"_key": "desc"
},
"size": 100000
},
"aggs": {
"4-metric": {
"max": {
"field": "value"
}
}
}
}
},
"size": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment