Created
October 27, 2018 17:57
-
-
Save gwbrown/7810da5ec1d3772f9a97e21f5b1c00e3 to your computer and use it in GitHub Desktop.
Sum of min_by in Elasticsearch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
GET testindex/_search | |
{ | |
"size": 0, | |
"aggs": { | |
"names": { | |
"terms": { | |
"field": "name.keyword" | |
}, | |
"aggs": { | |
"oldest_amount": { | |
"scripted_metric": { | |
"map_script": """ | |
if (state.oldest_date == null | |
|| doc.date.value.isBefore(state.oldest_date)) { | |
state.oldest_date = doc.date.value; | |
state.amount = doc.amount.value; | |
}""", | |
"reduce_script": """ | |
return states | |
.stream() | |
.min(Comparator.comparing(i->i.oldest_date)) | |
.map(i->i.amount) | |
.get()""" | |
} | |
} | |
} | |
}, | |
"total_amount": { | |
"sum_bucket": { | |
"buckets_path": "names>oldest_amount.value" | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment