Creating and using custom functions in painless

so here is the thing , i have this long script that define variables of type
String[] words_var1 = new String[] {'word1','word1','word1'}
then i have this function that tries to assign the right word to the right doc based on an id like so

 
def addwords(id, words) {
    if (ctx._source.fiiled1.contains(id)) {

        if (ctx._source.fiiled2 == null) {
            ctx._source.fiiled2 = [];
        }
        ctx._source.fiiled2.addAll(Arrays.asList(words));
    }
};

 addwords(1, words_var1);

i'm not even sure what the error that i get mean and i can't find it cause the script is too long ,

 "script_stack": [
          """... def addwords(id, words) {
    if  ...""",
          "                             ^---- HERE"
        ],
 "caused_by": {
      "type": "illegal_argument_exception",
      "reason": "unexpected token ['('] was expecting one of [{<EOF>, ';'}]."
    }

so i never wrote painless before and i really can't find good examples about so don't go hard on me as i suspect that not the way to even define a function

I am not good at painless either but have done a little.

First question: are you trying to use in an ingest pipeline ..what is the context?

  1. Definitely look at the docs here

The example in detail here that shows the proper way to define a function you are missing the defs

def addwords(def id, def words) {

3 you can use the Dev Tools - Painless debugger to work on syntax

def addwords(def id, def words) {
    String[] fiiled2 = new String[] {'foo','bar','word1'};
    if (id.equals(1)) {
      return fiiled2[id];
    }
    return words[id];
}

String[] words_var1 = new String[] {'word1','word1','word1'};
addwords(1, words_var1);

So you can use the debugger you will just need to substitute the context variables with some locals to debug ... then switch back to _ctx.

1 Like

thanks for the help @stephenb , that solved the syntax issues plus i had to move variables declarations to after declaring the function.

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