Looping through hits using painless script

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;"
		}

Thanks

I'm not entirely clear on what you are trying to accomplish. If you are looking to calculate the difference between each resulting item based upon the query criteria, you would likely need to use a scripted aggregation.
https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-metrics-scripted-metric-aggregation.html

1 Like

How will that turn out if the field is a Timestamp field. During the combine phase of Scripted metric aggregation. if the data is randomly stored across the shards then there is a possibility of overlapping ranges.

Shard A:

"params" : {

  "_agg" : {

    "transactions" : [ 1/01/2018, 5/01/2018]

  }

}

Shard B:

"params" : {

"_agg" : {

"transactions" : [ 2/01/2018, 4/01/2018 ]

}

}

if the map function is to subtract the results in each shard.

result of shard A is [4]

result of shard B is [2]

and final reduce function is to calculate sum of results from above 2 shards.

{

"results": 6

}

when it should have been 4 months.

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