Split string in scripted fields, using _ as a delimiter

In case this might be useful for someone else, I finally managed to solve the problem by employing path.indexOf('_') and a few more things. This solution can be adapated for any number of splits. That is, in my case, I had to split a string into 5 different parts, given four occurrences of _. This solution can be adaptad for any other number of parts.

To create newfield_one:

def newfield_one = ""; 
def path = doc["myfield.keyword"].value;
def first = path.indexOf("_");
if ()
{newfield_one = path.substring(0,first);}
else{newfield_one = 0;}
return newfield_one

For newfield_two:

def newfield_two = ""; 
def path = doc["myfield.keyword"].value;
def first = path.indexOf('_');
def second = first+1 + path.substring(first + 1).indexOf('_);
if (...)
{newfield_two = path.substring(first +1, second);}
else{newfield_two = 0}:
return new field

For the last, newfield_last:

def newfield_last = "";
def path = doc["myfield.keyword"].value;
def last = path.lastIndexOf('_');
if(...)
{newfield_last = path.substring(last+1);}
else{newfield_last = 0;}
return newfield_last

I am grateful for Val's help, here.

1 Like