I’ve been playing around with script fields to manipulate data returned by ElasticSearch queries. As an example, data where there are a few nested objects with values that need to be multiplied together:
{
"order": {
"item1": {
"cost": 31.55,
"count": 111
},
"item2": {
"cost": 62.55,
"count": 222
},
"item3": {
"cost": 93.55,
"count": 333
}
}
}
And to retrieve records and multiply cost by count:
{
"query" : { "match_all" : {} },
"_source": ["order.item*.item", "order.item*.count", "order.item*.cost"],
"script_fields" : {
"total_cost_1" : {
"script" :
{
"lang": "painless",
"source": "return doc['order.item1.cost'].value * doc['order.item1.count'].value;"
}
},
"total_cost_2" : {
"script" :
{
"lang": "painless",
"source": "return doc['order.item2.cost'].value * doc['order.item2.count'].value;"
}
},
"total_cost_3" : {
"script" :
{
"lang": "painless",
"source": "return doc['order.item3.cost'].value * doc['order.item3.count'].value;"
}
}
}
}
Unfortunately, I cannot find any way to iterate across an arbitrary number of item# objects nested in the order object. So, for now, I think the data manipulation will be done in the program using the API to retrieve data. Still, it was good to learn how to address values in the doc record.