Tomer
Tomer

Reputation: 2448

Elasticsearch - Using groovy script within function_score and access field payload

I am trying to understand what is the best way to access the payload while using groovy script.

I want to do something like this:

sum = 0;
categories  = doc['category'].values; 
for (category in categories){
   sum += category.payload
}
return sum;

Edit: Thanks to @Val and @Lee H I got to this point where I can actually access the payloads. But the suggested solution was to use _index which is not what I am looking for, _index give access to statistics in the scope of the index, and not for a specific document.

I want to go over every document, and take its payload and multiply it with some constant lets say.

when doing this: _index['category'].get('term', _PAYLOADS) I will get a list of all payloads of "term", which will is not what I am looking for.

So is there a way to access a field payload from the scope of a document?

Upvotes: 0

Views: 351

Answers (2)

Val
Val

Reputation: 217554

You can achieve this using advanced scripting and the _index context variable.

And Groovy is here to help with a nice one-liner:

return _index['category'].get('term', _PAYLOADS).sum {it.payloadAsInt(0)}

Upvotes: 1

Lee H
Lee H

Reputation: 5177

Check out the documentation for term positions and payloads it shows an example accessing the payloads for a field

Copying the last example here:

Example: sums up all payloads for the term foo.

termInfo = _index['my_field'].get('foo',_PAYLOADS);
score = 0;
for (pos in termInfo) {
    score = score + pos.payloadAsInt(0);
}
return score;

Upvotes: 1

Related Questions