Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
162 changes: 162 additions & 0 deletions explore-analyze/scripting/painless-array-list-manipulation-errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
---
navigation_title: Array manipulation errors
applies_to:
stack: ga
serverless: ga
products:
- id: elasticsearch
---

# Debug array manipulation errors in Painless

An array `index_out_of_bounds_exception` error occurs when a script tries to access an element at a position that does not exist in the array. For example, if an array has two elements, trying to access a third element triggers this exception.

Follow these guidelines to avoid array (list) access errors in your Painless scripts:

* **Array bounds:** Always check the size of an array before accessing specific indices.
* **Zero-indexed:** Remember that arrays start at index 0, so `size() - 1` is the last valid index.
* **Empty arrays:** Handle cases where arrays might be completely empty (`size() == 0`).

For details, refer to the following sample error, solution, and the result when the solution is applied to a sample document.

## Sample error

```json
{
"error": {
"root_cause": [
{
"type": "index_out_of_bounds_exception",
"reason": "index_out_of_bounds_exception: Index 2 out of bounds for length 2"
}
],
"type": "search_phase_execution_exception",
"reason": "all shards failed",
"phase": "query",
"grouped": true,
"failed_shards": [
{
"shard": 0,
"index": "blog_posts",
"node": "hupWdkj_RtmThGjNUiIt_w",
"reason": {
"type": "script_exception",
"reason": "runtime error",
"script_stack": [
"java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:100)",
"java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106)",
"java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302)",
"java.base/java.util.Objects.checkIndex(Objects.java:365)",
"java.base/java.util.ArrayList.get(ArrayList.java:428)",
"""return keywords[2].toUpperCase();
""",
" ^---- HERE"
],
"script": " ...",
"lang": "painless",
"position": {
"offset": 76,
"start": 61,
"end": 105
},
"caused_by": {
"type": "index_out_of_bounds_exception",
"reason": "index_out_of_bounds_exception: Index 2 out of bounds for length 2"
}
}
}
],
"caused_by": {
"type": "index_out_of_bounds_exception",
"reason": "index_out_of_bounds_exception: Index 2 out of bounds for length 2"
}
},
"status": 400
}
```

## Problematic code

```json
{
"aggs": {
"third_tag_stats": {
"terms": {
"script": {
"source": """
def keywords = params._source.tags;

return keywords[2].toUpperCase();
""",
"lang": "painless"
}
}
}
}
}
```

The error occurs because the script tries to access index 2 (the third element) in an array that only has two elements (indices 0, 1). Arrays in Painless are zero-indexed, so accessing an index greater than or equal to the array size causes an exception.

## Solution: Check an array's bounds before accessing it

Always verify the size of an array before accessing specific indices:

```json
GET blog_posts/_search
{
"size": 0,
"aggs": {
"third_tag_stats": {
"terms": {
"script": {
"source": """
def keywords = params._source.tags;

if (keywords.size() > 2) {
return keywords[2].toUpperCase();
} else {
return "NO_THIRD_TAG";
}
""",
"lang": "painless"
}
}
}
}
}
```

## Sample document

```json
POST blog_posts/_doc
{
"title": "Getting Started with Elasticsearch",
"content": "Learn the basics...",
"tags": ["elasticsearch", "tutorial"]
}
```

## Result

```json
{
...,
"hits": {
...
},
"aggregations": {
"third_tag_stats": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "NO_THIRD_TAG",
"doc_count": 1
}
]
}
}
}
```
110 changes: 110 additions & 0 deletions explore-analyze/scripting/painless-date-math-errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
---
navigation_title: Date math errors
applies_to:
stack: ga
serverless: ga
products:
- id: elasticsearch
---

# Debug date math errors in Painless

When you work with date fields in runtime mappings, accessing methods directly on the document field object can cause errors if the proper value accessor is not used.

Follow these guidelines to avoid [date](elasticsearch://reference/scripting-languages/painless/using-datetime-in-painless.md) operation errors in your Painless scripts:

* Always use `.value` when accessing single values from document fields in Painless.
* Check for empty fields when the field might not exist in all documents.
* Date arithmetic should be performed on the actual date value, not the field container object.

For details, refer to the following sample error and solution.

## Sample error

```json
{
"error": {
"root_cause": [
{
"type": "script_exception",
"reason": "runtime error",
"script_stack": [
"""emit(orderDate.toInstant().toEpochMilli() + 14400000);
""",
" ^---- HERE"
],
"script": " ...",
"lang": "painless",
"position": {
"offset": 75,
"start": 61,
"end": 124
}
}
],
"type": "search_phase_execution_exception",
"reason": "all shards failed",
"phase": "query",
"grouped": true,
"failed_shards": [
{
"shard": 0,
"index": "kibana_sample_data_ecommerce",
"node": "CxMTEjvKSEC0k0aTr4OM3A",
"reason": {
"type": "script_exception",
"reason": "runtime error",
"script_stack": [
"""emit(orderDate.toInstant().toEpochMilli() + 14400000);
""",
" ^---- HERE"
],
"script": " ...",
"lang": "painless",
"position": {
"offset": 75,
"start": 61,
"end": 124
},
"caused_by": {
"type": "illegal_argument_exception",
"reason": "dynamic method [org.elasticsearch.index.fielddata.ScriptDocValues.Dates, toInstant/0] not found"
}
}
}
]
},
"status": 400
}
```

## Problematic code

```json
"script": {
"lang": "painless",
"source": """
def orderDate = doc['order_date'];
emit(orderDate.toInstant().toEpochMilli() + 14400000);
"""
}
```

## Root cause

The script attempts to call `toInstant()` directly on a `ScriptDocValues.Dates` object. Date fields in Painless require accessing the `.value` property to get the actual date value before calling date methods.

## Solution

Access the date value using `.value` before calling date methods:

```json
"script": {
"lang": "painless",
"source": """
def orderDate = doc['order_date'].value; // Appended `.value` to the method.
emit(orderDate.toInstant().toEpochMilli() + 14400000);
"""
}
```

28 changes: 28 additions & 0 deletions explore-analyze/scripting/painless-debugging.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
navigation_title: Debugging Painless scripts
applies_to:
stack: ga
serverless: ga
products:
- id: elasticsearch
---

# Debug Painless scripts in {{es}}

Use the topics in this section to debug common errors in your [Painless](/explore-analyze/scripting/modules-scripting-painless.md) scripts.

* [Array/list manipulation errors](/explore-analyze/scripting/painless-array-list-manipulation-errors.md)
* [Date math errors](/explore-analyze/scripting/painless-date-math-errors.md)
* [Field not found (mapping conflicts)](/explore-analyze/scripting/painless-field-not-found.md)
* [Ingest pipeline failures](/explore-analyze/scripting/painless-ingest-pipeline-failures.md)
* [Null pointer exceptions](/explore-analyze/scripting/painless-null-pointer-exceptions.md)
* [Regex pattern matching failures](/explore-analyze/scripting/painless-regex-pattern-matching-failures.md)
* [Runtime field exceptions](/explore-analyze/scripting/painless-runtime-field-exceptions.md)
* [Sandbox limitations](/explore-analyze/scripting/painless-sandbox-limitations.md)
* [Script score calculation errors](/explore-analyze/scripting/painless-script-score-calculation-errors.md)
* [Subfield access](/explore-analyze/scripting/painless-subfield-access.md)
* [Type casting issues](/explore-analyze/scripting/painless-type-casting-issues.md)

## Additional resources
* [Introduction to Painless](/explore-analyze/scripting/modules-scripting-painless.md)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it a bit odd to link to the parent section? (Are we operating under the every page is page one assumption?)

I do think we should link the other way around, from the Introduction to Painless to the debugging section, maybe in the Start scripting section?

* [A Brief Painless walkthrough](elasticsearch://reference/scripting-languages/painless/brief-painless-walkthrough.md)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not related to this PR but I noticed that the title on this page doesn't capitalise Painless

Loading
Loading