A Brief Introduction to Scripting in ElasticSearch

Posted By : Asheesh Bhuria | 29-Aug-2019

Scripting is a very interesting feature in Elasticsearch which allows us to evaluate custom expressions. We can use scripting to either evaluate a custom score for a query or to return script fields in the result. This way we can save a lot of computation to filter out the result we get from Elasticsearch. Using scripting, we can perform calculations on fields, store them and even sort the ElasticSearch response based on the calculated fields!

 

Languages available in scripting

There are multiple languages that we can use for scripting, which include - Painless, Java, Mustache and Expression. The default language is painless. Painless is very similar to Java in terms of syntax, as it extends a particular set of Java’s syntax. 

 

Use Cases of scripting

There are several use cases for script. To name a few:- 

  • Creating new custom fields (derived from existing fields in ElasticSearch).
  • Sorting custom fields

 

Syntax for writing script query

The syntax for script query is quite straightforward, 

  "script": {
    "lang":   "...",  
    "source" : "...", 
    "params": { 
             ... 
            } 
  }
  • ‘lang’ is the language for scripting, for example - ‘painless’, ‘expression’, etc.
  • ‘source’ is the script itself
  • ‘params’ is an object which contains different parameters which we can use in our script

 

Please note that it is very important to make use of params rather than using some hard-coded value in the script. Whenever Elasticsearch sees a new script it compiles it and stores the compiled version of the script in a cache. And, of course compilation is a heavy process. 

 

Example

The following derives a new field - ‘fullname’ by combining ‘firstName’ and ‘lastName’,

{

  "query": {

    "match_all": {}

  },

  "script_fields": {

    "fullName": {

      "script": {

        "lang": "painless",

        "source": "doc['firstName.keyword'].value + ' ' + doc['lastName.keyword'].value"

      }

    }

  }

}

 

 

About Author

Author Image
Asheesh Bhuria

Asheesh Bhuria is a software engineer. With his knowledge in new technologies he excels in MEAN Stack development.

Request for Proposal

Name is required

Comment is required

Sending message..