Shorten your script
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 creatingruntime fields. Be mindful, however, that thefield access API is not a direct replacement fordoc. This shortened version of the original script includes a default value (thenull), so depending on the field type the script may access eitherdoc values or_source. Some fields will use_source as a fallback ifdoc values aren't available for a specific field.