Perform division of two fields in a Kibana visualisation

I'm unable to perform a basic division of two fields on Kibana. First, I tried to do so in a Line Chart bu using the Advanced Json Input section with this script:
{"script": "if(doc[''].value > 0) then {(doc['kpi.def'].value / doc[''].value)*100}"}
but I received 'esaggs' error.
When I tried to create a scripted field in the index using these codes:

if (doc[''].value > 0) { 
  return (doc['kpi.def'].value / doc[''].value);


doc[''].value > '0' ? doc['kpi.def'].value / doc[''].value : doc[''].value == '0' ? '0'

I still received errors. How can I resolve this?

There are probably documents in your index which don't have a value for kpi.NLAPAG1LOTOT - make sure to only access values in documents where they exist by appending this to the script:

if(doc["kpi.NLAPAG1LOTOT"].size()==0) { return null }

make sure to do this for all fields you are using in your script.

The first script you pasted is correct - in the second you are comparing with a string '0' instead of the number zero.

Hey, thanks for the response. I've implemented your suggestion and am using this code in my line chart visualisation, but still facing an issue with it : esaggs error

{"script": "if(doc[''].size()==0) {return null} else if (doc[''].value > 0) {return (doc['kpi.def'].value / doc[''].value)*100}"}

Additionally, my scripted field is made now but gives no output:

if(doc[""].size()==0) { return null; }
else if (doc[''].value > 0) { 
  return (doc['kpi.def'].value / doc[''].value)*100;}
if(doc[""].size()==0) { return null; }
else if (doc[''].value > 0) { 
  return (doc['kpi.def'].value / doc[''].value)*100;

This is the scripted field. Sorry, it didn't get uploaded in my previous reply.

The script in advanced json won't work, the scripted field is the right approach here. Please add a similar check for the kpi.NLAPAG1LOTOT and remove the script from advanced json (just select the scripted field from the dropdown)

1 Like

Ok, thanks a lot!

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