Error log: This error appears as the root_cause of a query failure when you’re using a script (e.g., in a script_score, script_field, or update query).
JSON
None
{
"error": {
"root_cause": [
{
"type": "script_exception",
"reason": "runtime error",
"script_stack": [
"if (doc['my_field'].value > 10) { ...", // <-- Your script " ^---- HERE" // <-- Where it failed ], "script": "if (doc['my_field'].value > 10) { ... }", "lang": "painless", "caused_by": { "type": "null_pointer_exception", // <-- The REAL reason "reason": "Cannot invoke \">\" on null" } } ], ... }, "status": 400 }
Why… is this happening? Your “Painless” script has a bug. Painless is the scripting language used by OpenSearch. Like any code, it can have syntax errors or runtime errors.
The error response gives you all the clues:
type: "script_exception": Confirms the problem is in your script.script_stack: Points to the exact line and character in your script that failed.caused_by: This is the most important part. It gives you the Java-level exception. In the example, it’s aNullPointerException(NPE).
This NPE happened because the script tried to run doc['my_field'].value (to get the field’s value), but for at least one document in the query, the my_field field was null (it didn’t exist or had no value). The script then tried to check if null > 10, which causes the error.
Best Practice:
- Code defensively (Check for nulls): Always assume a field might be missing. Before accessing a field’s value, check if it exists.
- Bad:
if (doc['my_field'].value > 10) ... - Good:
if (doc['my_field'].size() > 0 && doc['my_field'].value > 10) ... - The
doc['field_name'].size() > 0check is the standard way to verify a field exists and is not null before trying to get its.value.
- Bad:
- Use the
?.(Safe Navigation) Operator: Painless supports the “safe navigation” operator.- Good:
if (doc['my_field']?.value > 10) ... - The
?.will stop execution ifdoc['my_field']is null and will not try to access.value, preventing the NPE.
- Good:
- Test in dev tools: Use the
POST _scripts/painless/_executeAPI to test your script with sample documents before using it in a real query. This gives you a much faster debugging loop.
What else can I do? Stuck on a tricky Painless script? The Painless language documentation is your best resource. You can also post your script and the error on the OpenSearch community forums for help. For direct support, contact us in The OpenSearch Slack Channel in #General.