2

Is there a way In Elasticsearch 5.3 to loop through query results using painless script to compute difference between the hits returned by query.

I was trying to loop through the results in a for loop in script and could not what entity to loop on, i was hopping that scripts have something like the update api has ctx.payload.hits.hits that can be used in for loop.

"script": {
        "lang": "painless",
        "inline": "int total = 0; for (int i = 0; i <  ??? ; i++) { total +=  ???[i]._source['age'].value; } return total;"
    }
Bartors
  • 180
  • 1
  • 16
kiran6
  • 1,247
  • 2
  • 13
  • 19

1 Answers1

0

I have been facing the same problem and I found this thred on elastic forums. It looks like using map-reduce is the simplest way to achive "iteration through hits" as I have not found anything else. As the qquestion on elastic is exactly the same as yours I guess that you have written it, and the follow up question as well.

The question is a bit unclear on what is to the final goal but I do suggestto familiarize you with MapReduce as it looks like the Scripted metric Aggregation is based upon it. But, reading from the documentation it looks like the implementation is quite different as, I quote,:

Executed once on the coordinating node after all shards have returned their results. The script is provided with access to a variable _aggs which is an array of the result of the combine_script on each shard. If a reduce_script is not provided the reduce phase will return the _aggs variable.

So it looks to me as the "reduce job" is performed on one single node after the map_script (and the optional combine_script) has been performed. This way you could collect all the needed data in a map_script and have logic in reduce_script. But I have to emphasize that I have not a lot experience with those kind of things and have into some (different) trouble myself.

Bartors
  • 180
  • 1
  • 16