Elastic Search: How to write multi statement scripts?

You simply need to separate each statement with a semicolon:

"script": {
    "script": "isCompleted = doc['state'].value == 'completed'; preSLA = doc['lastStateUpdate'].value < doc['dueDate'].value; return isCompleted && preSLA;"
    }

Make sure to not add line breaks inside your script string, though, as it would not be valid JSON.


If you want to break your script into multiple lines you have to surrond your script with """ docs

`"query": {
    "function_score": {
      "script_score": {
        "script": {
          "lang": "painless",
          "source": """
            int total = 0;
            for (int i = 0; i < doc['goals'].length; ++i) {
              total += doc['goals'][i];
            }
            return total;
          """
        }
      }
    }
  }
}`

Update: For some versions of Elasticsearch source should be replaced with inline docs