Syntax error in painless script in watcher

Hello!
I'm trying to create a watcher with a condition that uses a Map and keep getting a syntax error.
For example the following code does not compile:

  "condition": {
    "script": {
      "source": """
        Map test = [:];
        for (entry in test.entrySet())
        {
            
        }
        return false;
        """,
      "lang": "painless"
    }

I tried various combination of "for (t in test)" or "for (def t : test)", but the only thing that works is:

        Map test = [:];
        for (def i=0; i<test.size(); i++)
        {
            
        }

But I'm confused how I am supposed to access the keys from there.
What is the proper way to access a key/value object like Map in this context?

Thank you for your help!

Hi @bcaillat,
It would be helpful if you posted the actual syntax errors.

Painless does not allow empty foreach loops, which is the problem with the condition script you've posted.

For looping over a map, you can either iterate over the key set or the entry set.

POST _scripts/painless/_execute
{
  "script": {
    "source": """
        Map test = ["A":"B", "C":"D"];
        String out = "";
        for (entry in test.entrySet())
        {
          out += "[" + entry.getKey() + "::" + entry.getValue() + "] ";
        }
        for (key in test.keySet()) {
          out += "(" + key + "," + test[key] + ") "
        }
        return out;
    """
  }
}

Result: "[A::B] [C::D] (A,B) (C,D) "

Hello @stu ,

thank you so much for your answer. The issue was that my for loop was empty (as I was very ironically just testing the syntax)! As soon as I added a line between the {}, it worked.
That sounds like a bug in painless interpreter; I would assume that a language should allow empty loop.
Anyway, thanks a lot for your reply, I was stuck on that for a while!

Ben

Thanks for circling back. It's an intentional feature to enhance usability and performance. In many painless contexts, the script will run once per document and there may be millions of documents.

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