Aggregating array objects using scripted field

Hello everyone!

I'm trying to do a transformation in an array object and I'm get stucked. Can anyone help me to figure it out ?

I'm aware that the better solution is doing the "denormalization" of this array as @Joe_Fleming said in another topic, but, unfortunately, it can't be done right now. (read about it here

the evil object

painless script that isn't working and are giving me a headache.
def l = new ArrayList();
if(!doc.containsKey('details.plan_op_nature')){return 0;}else{
for(int i = 0;i<doc['details.plan_orders'].values.length;i++){
l.add(doc['details.plan_orders_product_quantity'].values[i]);
}
return sum(l);
}

The desired result when doc contains the field plan_op_nature:
the sum of all objects in the array l (in the case of the image, it should be 15000)

Thx a lot for your time!

Hi @Thayan_Oliveira,

If you create your scripted fields you can do a test run by clicking the "
Get help with the syntax and preview the results of your script." button and switching to the "Preview Results" tab. What are you seeing there?

A few things I already noticed about your script:

  • You can directly sum up the values, no need to collect them in a array list first
  • It should be details.plan_orders.product_quantity (note the dot instead of the underscore)

Could you try this script:

if(!doc.containsKey('details.plan_op_nature')){
  return 0;
} else {
  def res = 0;
  for(int i = 0;i<doc['details.plan_orders.product_quantity'].values.length;i++){
    res +=doc['details.plan_orders.product_quantity'].values[i];
  }
  return res;
}

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