this painless script will do this:
(It's not required on Terms aggregation. It does the same job, but accumulating all inside a string. (Here I need item field of my document)
"stringified": {
"scripted_metric": {
"init_script" : "params._agg.terms = new HashMap();",
"map_script" : " String v = doc['item.keyword'].value; if (!params._agg.terms.containsKey(v)) { params._agg.terms[v] = 0 } params._agg.terms[v]++",
"combine_script" : "def acc = new HashMap(); for (entry in params._agg.terms.entrySet()) { if (!acc.containsKey(entry.getKey())) {acc[entry.getKey()] = entry.getValue()} else {acc[entry.getKey()] += entry.getValue()} } return acc",
"reduce_script":"String result = '{'; def acc = new HashMap(); for (agg in params._aggs) { for (entry in agg.entrySet()) { if (!acc.containsKey(entry.getKey())) { acc[entry.getKey()] = entry.getValue() } else { acc[entry.getKey()] += entry.getValue() } } } for (a in acc.entrySet()) { result += '\"' + a.getKey() + '\":' + String.format('%d', new def[] {a.getValue()}) + ', ' } return result + '}'"
}
}