Shorten your script
Elastic Cloud Serverless projects are autoscaled environments, fully managed by Elastic and available on Elastic Cloud. Availability This functionality is generally available and ready for production usage. Serverless interfaces and procedures might differ from classic Elastic Stack deployments. The Elastic Stack includes Elastic's core products such as Elasticsearch, Kibana, Logstash, and Beats. Availability This functionality is generally available and ready for production usage. Unless stated otherwise on the page, this functionality is available when your Elastic Stack is deployed on Elastic Cloud Hosted, Elastic Cloud Enterprise, Elastic Cloud on Kubernetes, and self-managed environments. This documentation corresponds to the latest patch available for each minor version. If you're not using the latest patch, check the release notes for changes.
Serverless
Generally available
Stack
Generally available
Using syntactic abilities that are native to Painless, you can reduce verbosity in your scripts and make them shorter. Here’s a simple script that we can make shorter:
GET my-index-000001/_search{ "script_fields": { "my_doubled_field": { "script": { "lang": "painless", "source": "return doc['my_field'].value * params.get('multiplier');", "params": { "multiplier": 2 } } } } }
Let’s look at a shortened version of the script to see what improvements it includes over the previous iteration:
GET my-index-000001/_search{ "script_fields": { "my_doubled_field": { "script": { "source": "field('my_field').get(null) * params['multiplier']", "params": { "multiplier": 2 } } } } }
This version of the script removes several components and simplifies the syntax significantly:
- The
langdeclaration. Because Painless is the default language, you don’t need to specify the language if you’re writing a Painless script. - The
returnkeyword. Painless automatically uses the final statement in a script (when possible) to produce a return value in a script context that requires one. - The
getmethod, which is replaced with brackets[]. Painless uses a shortcut specifically for theMaptype that allows us to use brackets instead of the lengthiergetmethod. - The semicolon at the end of the
sourcestatement. Painless does not require semicolons for the final statement of a block. However, it does require them in other cases to remove ambiguity.
You can use this abbreviated syntax anywhere that Elasticsearch supports scripts, such as when you’re creating runtime fields. Be mindful, however, that the field access API is not a direct replacement for doc. This shortened version of the original script includes a default value (the null), so depending on the field type the script may access either doc values or _source. Some fields will use _source as a fallback if doc values aren't available for a specific field.