Search code examples
elasticsearchlucenekibanakibana-4

Scripted Fields for if/else condition in Kibana 4


I have some numeric fields in elasticsearch, I have to implement some logic for which I need to create some scripted fields. I am new to kibana 4's scripted fields feature, so I need some help regarding a basic format that could be used for writing a basic if else condition in scripted fields.

Detailed explanation: I have a number field x in elasticsearch, I need to create two scripted fields f1 and f2 such that,

if x==0
  f1 = 1  and  f2 = 0
else
  f1 = 0  and  f2 = 1

Just need the correct syntax to do this in Kibana 4's scripted fields feature. Also tell if this can't be done.
For more information on scripted fields refer : https://www.elastic.co/guide/en/kibana/current/settings.html


Solution

  • To create a scripted field, you go into the Settings for the index and click on the Scripted Fields tab. Hit Add Scripted Field.

    In your case, you will enter f1 as the Name and doc['x'].value == 0 ? 1 : 0 as the Script. You'll then add a second scripted field with f2 as the Name and doc['x'].value != 0 ? 1 : 0 as the script.

    The ?: is the ternary operator and works like in most languages -- it evaluates the condition before the ? and if the value is true the expression has the value of whatever is after the ? and if it's false, it has the value of whatever is after the :.