Skip to content

Instantly share code, notes, and snippets.

@gwbrown
Created October 27, 2018 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gwbrown/7810da5ec1d3772f9a97e21f5b1c00e3 to your computer and use it in GitHub Desktop.
Save gwbrown/7810da5ec1d3772f9a97e21f5b1c00e3 to your computer and use it in GitHub Desktop.
Sum of min_by in Elasticsearch
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