Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
7598b39
[DRAFT] Painless docs overhaul (reference)
Oct 27, 2025
eeee63e
add applies-to tags
Oct 27, 2025
5a639e7
add operations
Nov 3, 2025
ea47019
Merge branch 'main' into painless003
kilfoyle Nov 5, 2025
40e3e0f
add pages
Nov 5, 2025
e9d7f4b
fix image
Nov 6, 2025
5ac1b57
some of the specs
Nov 6, 2025
b505f3c
fix ref intro links
Nov 6, 2025
0495d3e
fix links
Nov 6, 2025
9f97b33
Merge branch 'main' into painless003
kilfoyle Nov 6, 2025
12f9bca
link fix
Nov 6, 2025
e8f17ec
more specs
Nov 7, 2025
bd76dfc
operators caps fixes
Nov 7, 2025
60d0118
touchup
Nov 7, 2025
678d872
Add operators, etc.
Nov 18, 2025
06fe17c
Merge branch 'main' into painless003
kilfoyle Nov 19, 2025
649031f
Some contexts
Nov 19, 2025
801701b
four more contexts
Nov 19, 2025
8e21afc
More contexts
Nov 20, 2025
4c8dcee
more contexts
Nov 24, 2025
09a5558
Merge branch 'main' into painless003
kilfoyle Nov 25, 2025
328012a
link fix
Nov 25, 2025
969700f
style / format fixes
Nov 25, 2025
36a2cac
more edits
Nov 26, 2025
ed2b6a4
Merge branch 'main' into painless003
kilfoyle Nov 26, 2025
4523a9a
Add missing example code for aggregation combine context
Dec 2, 2025
f6af742
Merge branch 'main' into painless003
kilfoyle Dec 2, 2025
84e4dbb
Merge branch 'main' into painless003
kilfoyle Dec 8, 2025
ff7470b
Merge branch 'main' into painless003
kilfoyle Jan 15, 2026
9a9c099
Address feedback
Jan 15, 2026
89a048d
Address Jack's suggestions
Jan 16, 2026
c51207f
Add link to datetime docs
Jan 16, 2026
8294ae4
Add Kibana requirement note
Jan 16, 2026
e4b0962
Merge branch 'main' into painless003
kilfoyle Jan 21, 2026
18fd544
fix last review comments
Jan 21, 2026
69cd4a0
Merge branch 'main' into painless003
kilfoyle Jan 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ Use the filter if you want to narrow the item set analysis to fields of interest

### Examples [frequent-item-sets-example]

In the following examples, we use the e-commerce {{kib}} sample data set.
The following examples use the {{kib}} eCommerce sample data set.


### Aggregation with two analyzed fields and an `exclude` parameter [_aggregation_with_two_analyzed_fields_and_an_exclude_parameter]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/painless/current/painless-walkthrough.html
applies_to:
stack: ga
serverless: ga
products:
- id: painless
---

:::{tip}
This walkthrough is designed for users experienced with scripting and already familiar with Painless, who need direct access to Painless specifications and advanced features.

<!--
If you're new to Painless scripting or need step-by-step guidance, start with [How to write scripts](docs-content://explore-analyze/scripting/modules-scripting-using) in the Explore and Analyze section for a more accessible introduction.
-->

:::

# A brief painless walkthrough [painless-walkthrough]

To illustrate how Painless works, let’s load some hockey stats into an Elasticsearch index:
To illustrate how Painless works, let’s load some hockey stats into an {{es}} index:

```console
PUT hockey/_bulk?refresh
Expand Down Expand Up @@ -36,276 +48,10 @@ PUT hockey/_bulk?refresh
```
% TESTSETUP

## Accessing Doc Values from Painless [_accessing_doc_values_from_painless]

Document values can be accessed from a `Map` named `doc`.

For example, the following script calculates a player’s total goals. This example uses a strongly typed `int` and a `for` loop.

```console
GET hockey/_search
{
"query": {
"function_score": {
"script_score": {
"script": {
"lang": "painless",
"source": """
int total = 0;
for (int i = 0; i < doc['goals'].length; ++i) {
total += doc['goals'][i];
}
return total;
"""
}
}
}
}
}
```

Alternatively, you could do the same thing using a script field instead of a function score:

```console
GET hockey/_search
{
"query": {
"match_all": {}
},
"script_fields": {
"total_goals": {
"script": {
"lang": "painless",
"source": """
int total = 0;
for (int i = 0; i < doc['goals'].length; ++i) {
total += doc['goals'][i];
}
return total;
"""
}
}
}
}
```

The following example uses a Painless script to sort the players by their combined first and last names. The names are accessed using `doc['first'].value` and `doc['last'].value`.

```console
GET hockey/_search
{
"query": {
"match_all": {}
},
"sort": {
"_script": {
"type": "string",
"order": "asc",
"script": {
"lang": "painless",
"source": "doc['first.keyword'].value + ' ' + doc['last.keyword'].value"
}
}
}
}
```


## Missing keys [_missing_keys]

`doc['myfield'].value` throws an exception if the field is missing in a document.

For more dynamic index mappings, you may consider writing a catch equation

```
if (!doc.containsKey('myfield') || doc['myfield'].empty) { return "unavailable" } else { return doc['myfield'].value }
```


## Missing values [_missing_values]

To check if a document is missing a value, you can call `doc['myfield'].size() == 0`.


## Updating Fields with Painless [_updating_fields_with_painless]

You can also easily update fields. You access the original source for a field as `ctx._source.<field-name>`.

First, let’s look at the source data for a player by submitting the following request:

```console
GET hockey/_search
{
"query": {
"term": {
"_id": 1
}
}
}
```

To change player 1’s last name to `hockey`, simply set `ctx._source.last` to the new value:

```console
POST hockey/_update/1
{
"script": {
"lang": "painless",
"source": "ctx._source.last = params.last",
"params": {
"last": "hockey"
}
}
}
```

You can also add fields to a document. For example, this script adds a new field that contains the player’s nickname, *hockey*.

```console
POST hockey/_update/1
{
"script": {
"lang": "painless",
"source": """
ctx._source.last = params.last;
ctx._source.nick = params.nick
""",
"params": {
"last": "gaudreau",
"nick": "hockey"
}
}
}
```


## Dates [modules-scripting-painless-dates]

Date fields are exposed as `ZonedDateTime`, so they support methods like `getYear`, `getDayOfWeek` or e.g. getting milliseconds since epoch with `getMillis`. To use these in a script, leave out the `get` prefix and continue with lowercasing the rest of the method name. For example, the following returns every hockey player’s birth year:

```console
GET hockey/_search
{
"script_fields": {
"birth_year": {
"script": {
"source": "doc.born.value.year"
}
}
}
}
```


## Regular expressions [modules-scripting-painless-regex]

::::{note}
Regexes are enabled by default as the Setting `script.painless.regex.enabled` has a new option, `limited`, the default. This defaults to using regular expressions but limiting the complexity of the regular expressions. Innocuous looking regexes can have staggering performance and stack depth behavior. But still, they remain an amazingly powerful tool. In addition, to `limited`, the setting can be set to `true`, as before, which enables regular expressions without limiting them.To enable them yourself set `script.painless.regex.enabled: true` in `elasticsearch.yml`.
::::


Painless’s native support for regular expressions has syntax constructs:

* `/pattern/`: Pattern literals create patterns. This is the only way to create a pattern in painless. The pattern inside the `/’s are just [Java regular expressions](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.md). See [Pattern flags](/reference/scripting-languages/painless/painless-regexes.md#pattern-flags) for more.
* `=~`: The find operator return a `boolean`, `true` if a subsequence of the text matches, `false` otherwise.
* `==~`: The match operator returns a `boolean`, `true` if the text matches, `false` if it doesn’t.

Using the find operator (`=~`) you can update all hockey players with "b" in their last name:

```console
POST hockey/_update_by_query
{
"script": {
"lang": "painless",
"source": """
if (ctx._source.last =~ /b/) {
ctx._source.last += "matched";
} else {
ctx.op = "noop";
}
"""
}
}
```

Using the match operator (`==~`) you can update all the hockey players whose names start with a consonant and end with a vowel:

```console
POST hockey/_update_by_query
{
"script": {
"lang": "painless",
"source": """
if (ctx._source.last ==~ /[^aeiou].*[aeiou]/) {
ctx._source.last += "matched";
} else {
ctx.op = "noop";
}
"""
}
}
```

You can use the `Pattern.matcher` directly to get a `Matcher` instance and remove all of the vowels in all of their last names:

```console
POST hockey/_update_by_query
{
"script": {
"lang": "painless",
"source": "ctx._source.last = /[aeiou]/.matcher(ctx._source.last).replaceAll('')"
}
}
```

`Matcher.replaceAll` is just a call to Java’s `Matcher`'s [replaceAll](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.md#replaceAll-java.lang.String-) method so it supports `$1` and `\1` for replacements:

```console
POST hockey/_update_by_query
{
"script": {
"lang": "painless",
"source": "ctx._source.last = /n([aeiou])/.matcher(ctx._source.last).replaceAll('$1')"
}
}
```

If you need more control over replacements you can call `replaceAll` on a `CharSequence` with a `Function<Matcher, String>` that builds the replacement. This does not support `$1` or `\1` to access replacements because you already have a reference to the matcher and can get them with `m.group(1)`.

::::{important}
Calling `Matcher.find` inside of the function that builds the replacement is rude and will likely break the replacement process.
::::


This will make all of the vowels in the hockey player’s last names upper case:

```console
POST hockey/_update_by_query
{
"script": {
"lang": "painless",
"source": """
ctx._source.last = ctx._source.last.replaceAll(/[aeiou]/, m ->
m.group().toUpperCase(Locale.ROOT))
"""
}
}
```

Or you can use the `CharSequence.replaceFirst` to make the first vowel in their last names upper case:

```console
POST hockey/_update_by_query
{
"script": {
"lang": "painless",
"source": """
ctx._source.last = ctx._source.last.replaceFirst(/[aeiou]/, m ->
m.group().toUpperCase(Locale.ROOT))
"""
}
}
```

Note: all of the `_update_by_query` examples above could really do with a `query` to limit the data that they pull back. While you **could** use a [script query](/reference/query-languages/query-dsl/query-dsl-script-query.md) it wouldn’t be as efficient as using any other query because script queries aren’t able to use the inverted index to limit the documents that they have to check.
With the hockey data ingested, try out some basic operations that you can do in Painless:

- [](/reference/scripting-languages/painless/painless-walkthrough-access-doc-values.md)
- [](/reference/scripting-languages/painless/painless-walkthrough-missing-keys-or-values.md)
- [](/reference/scripting-languages/painless/painless-walkthrough-updating-fields.md)
- [](/reference/scripting-languages/painless/painless-walkthrough-dates.md)
- [](/reference/scripting-languages/painless/painless-walkthrough-regular-expressions.md)
Loading
Loading