# Scripted metrics

**URL:** https://discuss.elastic.co/t/scripted-metrics/95159
**Category:** Elasticsearch
**Created:** [July 31, 2017, 9:41am UTC](https://discuss.elastic.co/t/scripted-metrics/95159 "2017-07-31T09:41:06Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![marwa](https://avatars.discourse-cdn.com/v4/letter/m/67e7ee/32.png) [@marwa](https://discuss.elastic.co/u/marwa)
#### Post date: [July 31, 2017, 9:41am UTC](https://discuss.elastic.co/t/scripted-metrics/95159/1 "2017-07-31T09:41:07Z")

</div>

Hello ,  
i created an index with date, product and revenue fields. i need to calculate the total revenue made in 2016 then divide for each document that its product is sold in 2017 the revenue by the total revenue of 2016 . i am using the scripted metrics of elasticsearch 's aggregatons .  
it's my first time using it ,this the script

GET /retails\_transactions  
{  
"query": {  
"match\_all": {}  
},  
"aggs": {  
"revenue\_year\_to\_day": {  
"scripted\_metric": {  
"init\_script": "\_agg["tempArray"] = [];",  
"map\_script": "revenue\_previous\_year= 0;if ( doc.transaction\_date.value in [1-1-2016 ,12-30-2016]) { revenue\_previous\_year += doc.revenue.value } { \_agg.tempArray.add(revenue\_previous\_year); } ",  
"combine\_script": "revenue\_per\_ytd = 0; if ( doc.transaction\_date.value in [1-1-2017, 12-30-2017]){for (i in \_agg.tempArray) { revenue\_per\_ytd += doc.revenue.value / i }}; return revenue\_per\_ytd;",  
"reduce\_script": "revenue\_per\_ytd = 0; for (j in \_aggs) { revenue\_per\_ytd += doc.revenue.value /j }; return revenue\_per\_ytd ;"  
}  
}  
}  
}

it doesn't work and i don't get where maintains the problem ??

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)
#### Post date: [August 28, 2017, 9:41am UTC](https://discuss.elastic.co/t/scripted-metrics/95159/2 "2017-08-28T09:41:14Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
