How to create a scripted field with multiple conditions check?

Hi,

I am using ELK GA 5.0.0. In my index, I have a string field named name. I want to create a field named category based on the value of name. Below is the pseudo code;

if(name== 'elephant' || name== 'lion' || name== 'rabbit' || name== 'zebra' || name== 'monkey'){
    category = 'animals'
}else if(name== 'tuna' || name== 'whale' || name== 'shark'){
    category = 'fish'
}else if(name== 'cobra' || name== 'viper' || name== 'python' || name== 'mamba'){
    category = 'snake'
}else if(name== 'crocodile' || name== 'alligator'){
    category = 'reptile'
}else if(name== 'butterfly' || name== 'spider' || name== 'beetle' || name== 'bug' || name== 'dragonfly'){
    category = 'insect'
}else if(name== 'parrot' || name== 'eagle' || name== 'crow' || name== 'owl' || name== 'nightingale'){
    category = 'birds'
}else{
    category = 'others'
}

How can I create this field?

Thank you.

I more recent versions you should be able to do this using a scripted field using Painless. Not sure whether but is possible in earlier versions. In general it would however probably be faster and more efficient to add this as a field at index time.

Ok @Christian_Dahlqvist I refered that before, but how to create such a painless rule?

Well, first you probably need to upgrade to Elasticsearch 5.6 or 6.x as Painless is not available in Elasticsearch 5.0.0.

Ok, but previously, I have created fields like;

doc['category.keyword'].value == 'vegetable' || doc['category.keyword'].value == 'meat' ? 1 : 0

This is working fine for me.

Why not simply add this at index time?

Good question :stuck_out_tongue_winking_eye::+1:

But actually, my logstash is generic and taking much cpu already. Thought of adding this to logsatsh, so that I can easily modify my data accordingly, but there are reasons. My only possible hope is scripted field now, thats y :frowning:

This blog post provides a good introduction, and actually points out that Painless is available in version 5.0, so I was remembering wrong earlier.

Something like this may work (although I have not tested it):

def birds = ["parrot", "eagle", "crow"]; 
def insects = ["spider", "beatle];
if(birds.contains(doc["name"].value)) { 
    return "bird"; 
} else if (insects.contains(doc["name"].value) { 
    return "insect"; 
} else {
    return "other";
}
1 Like

Ok. Lemme see.

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