Stringify result of terms aggregation

Is it possible to use scripted metric aggregation to stringify the result of terms aggregation?
I have a terms aggregation that returns 20 buckets like:

            {
                                                    "key": "a",
                                                    "doc_count": 1155
                                                },
                                                {
                                                    "key": "b",
                                                    "doc_count": 291
                                                },
                                                {
                                                    "key": "c",
                                                    "doc_count": 232
                                                },
                                                {
                                                    "key": "d",
                                                    "doc_count": 202
                                                },
                                                {

I would like another aggregation that will return concatenated string, like "a(1155),b(291),c(232),d(202)"

Is it possible to do via script?

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 + '}'"
				            }
                            }

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