Search code examples
elasticsearchelasticsearch-painlessopensearch

OpenSearch script - accessing global variables inside a function


I'm writing some sorting scripts for OpenSearch (fork of ElasticSearch). The script environment defines some global constants, like doc, that are available at the top level of the script, but apparently not inside a function definition.

def getPrice() {
    return doc["price"];  // compile error: cannot resolve symbol [doc]
}

int price = doc["price"]; // this works

Can someone point me to the documentation which explains precisely where and when the globals are available? And is there any way to access doc inside a function, like adding a namespace prefix or something? (Obviously, I could pass it in as a function parameter, but I just want to see if that's really necessary.)


Solution

  • Opensearch scripts are based on Painless as well.

    Painless functions are not well documented, but they have been designed to be completely independent of the script body, so anything that the function should work on must be passed as parameters.

    def getPrice(Map document) {
        return document["price"];    
    }
    
    int price = getPrice(doc);