In a painless script how do I iterate through document keys based on a pattern?

Hello,

I would like to come up with a scripted field of sum of all values based on document keys. So for example I have the following k=v pairs.
doc['totalA'] = 1
doc['totalB'] = 3
doc['totalC'] = 3

I would like to sum all the values if the key matches total*. How do I go about this? I can obviously explicitly mention each document name, I just would like to match a pattern and sum it all if possible?

Thanks!

@gthang

Have you tried iterating over the doc map? https://www.elastic.co/guide/en/elasticsearch/painless/master/painless-field-context.html

Someone working through a similar problem - Loop over a map in Painless

If somebody stumbles into this when they ddg'ing or so,

I figured this out, I feel pretty dumb it took this long to figure something so simple out.

I found this documentation very useful.

double total = 0.0;
for (key in params._source.keySet()) {
    if (key.startsWith("total")) {
        total = total + doc[key].value;
    }
}

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