resp = client.search( index="ledger", size="0", query={ "match_all": {} }, aggs={ "profit": { "scripted_metric": { "init_script": "state.transactions = []", "map_script": "state.transactions.add(doc.type.value == 'sale' ? doc.amount.value : -1 * doc.amount.value)", "combine_script": "double profit = 0; for (t in state.transactions) { profit += t } return profit", "reduce_script": "double profit =
![Scripted metric aggregation | Elasticsearch Guide [8.16] | Elastic](https://cdn-ak-scissors.b.st-hatena.com/image/square/cbbc87b803e58787f8346841e5b65698d408f3c5/height=288;version=1;width=512/https%3A%2F%2Fwww.elastic.co%2Fstatic%2Fimages%2Felastic-logo-200.png)