(Painless) Scripting

Spatialized founder Jozef Sorocin
Jozef Soročin
Book a consultation ↗
4 min read  •  Updated 07/13/2025

Scripting enables you to evaluate custom expressions.

As explored in 2. Insertion & Ingestion , we can modify fields.

And as mentioned in Points Closest to the Origin , we can dynamically score documents and calculate new values on-the-fly.

Scripts can be used in various contexts but are leveraged most often:

  • during updates and reindexing
  • in queries and aggregations where there are no alternatives (like here )
  • and when sorting .

The default scripting language is Painless . Additional lang plugins enable you to run scripts written in other languages. Everywhere a script can be used, you can include a lang parameter to specify the language of the script.

  • groovy — slow and discontinued
  • painless — a sandboxed and secure general-purpose language extending a subset of Java's syntax; offers optional typing through the def keyword
  • expression — Lucene expressions — a sandboxed, javascript-like language used for fast custom ranking and sorting but limited to only numeric, boolean, date, and geo_point fields
  • mustache — used in (search) templates. Here's an example.
  • and good old java — supporting lower-level script engine modules

The script syntax always follows the same pattern:

"script": {
  "lang":   "...",
  "source": "...",
  "params": { ... }
}

though the source field is sometimes interchanged with id — denoting a Stored Script .

Short form (inline scripts) is also supported:

"script": "..."

but you'll lose access to the params dictionary.

Prefer params whenever possible! The first time Elasticsearch sees a new script, it compiles it and stores the compiled version in a cache — but note that compilation can be a heavy process.

If you need to pass variables into the script, you should pass them in as named params instead of hard-coding values into the script itself. This includes primitive variables but also items like the current timestamp, as discussed in Use Case #1 in Post-Indexing: Updates .

Scripts used in queries and aggregations will be executed once for every document which matches a query or is covered by an aggregation. Depending on how many documents you have, this could translate into millions or billions of executions — so these scripts need to be fast!

Join 200+ developers who've mastered this! Get Lifetime Access — $5
Already a member? Sign in here