Elasticsearch Groovy Script Syntax For Generation Of Nested Fields
Solution 1:
I think that initially your _source.Orders
field is null, i.e. not even an empty array.
Moreover, containsKey
might not be the right way to go, because your _source
might contain a field named Orders
whose type might not be an array, i.e. it might be a dynamic object standing for an existing order, or worse, just a plain string.
I suggest you try a different approach by first checking if Orders
is null and initialize it to an empty array if not. Then you can append the orderItem
to the resulting array:
{
"script" : "ctx._source.Orders = ((ctx._source.Orders ?: []) += orderItem)",
"params" : {
"orderItem" : orderItem
}
}
An alternative to this would be to simply ensure that when you index your document the first time, you make sure that the Orders
field is initialized with an empty array []
and then your script could simply append orderItems
to that array.
UPDATE
Based on your comments, I'm revising my answer in order to deal with the case where Orders
is a dynamic object containing shop names as keys and each of those keys points to an array of orders for that shop. It's basically the same idea as earlier, just that we need to deal with one more level (i.e. the shop names).
First the script makes sure that the Orders
object exists and then it makes sure that the shop array within the Orders
object exists as well. All that remains to do is to append the orderItem
to the shop array:
{
"script" : "ctx._source.Orders = ctx._source.Orders ?: [shopName:'']; ctx._source.Orders[shopName] = ((ctx._source.Orders[shopName] ?: []) + orderItem); ctx._source.TimestampUpdated = TimestampUpdated",
"params" : {
"shopName": shopName,
"orderItem" : orderItem,
"TimestampUpdated":datetime.now().isoformat()
}
}
Post a Comment for "Elasticsearch Groovy Script Syntax For Generation Of Nested Fields"