No scripted fields necessary. This nested sum aggregation should do the trick:
{
"size": 0,
"aggs": {
"builds": {
"terms": {
"field": "build_name"
},
"aggs": {
"total_durations_parent": {
"nested": {
"path": "projects"
},
"aggs": {
"total_durations": {
"sum": {
"field": "projects.project_duration_ms"
}
}
}
}
}
}
}
}
Your use case is a great candidate for employing the copy_to
parameter which'll put the build durations into one top-level list of longs so that the nested
query won't be required when we're summing them up.
Adjust the mapping like so:
"properties": {
"build_name": { "type": "keyword" },
"start_ms": { "type": "date" },
"total_duration_ms": { "type": "long" }, <--
"projects": {
"type": "nested",
"properties": {
"project_duration_ms": {
"type": "long",
"copy_to": "total_duration_ms" <--
},
"project_name": { "type": "keyword" }
}
}
}
After reindexing (which is required due to the newly added field), the above query gets simplified to:
{
"size": 0,
"aggs": {
"builds": {
"terms": {
"field": "build_name"
},
"aggs": {
"total_durations": {
"sum": {
"field": "total_duration_ms"
}
}
}
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…