How to grab subset parts of a string, using its keys to map onto return value

Trying to do something which should be simple. Using Painless, take a value like "1.4" and another like "1.5", and using the first and second number, pop the name from a dictionary. I know there are methods like substr, but I don't know how to use them properly.

def dict = ['1.4': spaceship, '1.5': satelite]
def strct = doc['entityType.keyword'].value;
def first = strct.indexOf('.');
def second = first + 1 + strct.substring(first +1).indexOf('.');
def value = strct[0:first] + '-' +strct[first:second]

You can do this in many ways, and I'm not sure about the content of your entityType field but in the Painless Lab application in the Dev Tools you can try easily to code different approaches that later you can adapt to your context.

For example this works for me:

def dict = ['1.4': 'spaceship', '1.5': 'satelite'];
def test_string = "A string with 1.5 on it";

for (key in dict.keySet()) {
    if ( test_string.contains(key) ) {
        return dict[key];

return "Not found

You could also use indexOf for sure.

def dict = ['1.4': 'spaceship', '1.5': 'satelite'];
def test_string = "A string with 1.5";

def from = test_string.indexOf('.');

if (from != -1){
    def key = test_string.substring(from - 1, from + 2 );
    def value = dict[key];
    if (value != null) {
        return value;

return "Not found"

Check all the methods available for strings at

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