You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/reference/scripting-languages/painless/painless-comments.md
+48-26Lines changed: 48 additions & 26 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -10,46 +10,68 @@ products:
10
10
11
11
# Comments [painless-comments]
12
12
13
-
Use a comment to annotate or explain code within a script. Use the `//` token anywhere on a line to specify a single-line comment. All characters from the `//` token to the end of the line are ignored. Use an opening `/*` token and a closing `*/` token to specify a multi-line comment. Multi-line comments can start anywhere on a line, and all characters in between the `/*` token and `*/` token are ignored. A comment is included anywhere within a script.
13
+
Comments are used to explain or annotate code and make it more readable. They are ignored when the script is executed, allowing you to add notes or temporarily disable code sections without affecting the functionality.
14
14
15
-
**Grammar**
15
+
Painless supports two types of comments: single-line comments and multi-line comments.
16
16
17
-
```text
17
+
## Single-line comments
18
+
19
+
Single-line comments start with `//` and continue to the end of the line. Everything after `//` on that line is ignored by the compiler.
20
+
21
+
### Grammar
22
+
23
+
```
18
24
SINGLE_LINE_COMMENT: '//' .*? [\n\r];
19
-
MULTI_LINE_COMMENT: '/*' .*? '*/';
20
25
```
21
26
22
-
**Examples**
27
+
### Example
23
28
24
-
* Single-line comments.
29
+
```
30
+
// This is a single-line comment
31
+
int value = 10;
32
+
int price = 100; // Comment at the end of a line
33
+
```
25
34
26
-
```painless
27
-
// single-line comment
35
+
## Multi-line comments
28
36
29
-
int value; // single-line comment
30
-
```
37
+
Multi-line comments start with `/*` and end with `*/`. Everything between these markers is ignored, even if it spans multiple lines.
31
38
32
-
* Multi-line comments.
39
+
### Grammar
33
40
34
-
```painless
35
-
/* multi-
36
-
line
37
-
comment */
41
+
```
42
+
MULTI_LINE_COMMENT: '/*' .*? '*/';
43
+
```
38
44
39
-
int value; /* multi-
40
-
line
41
-
comment */ value = 0;
45
+
### Example
46
+
47
+
```
48
+
/* This is a
49
+
multi-line comment
50
+
spanning several lines */
51
+
52
+
int total = price * quantity;
42
53
43
-
int value; /* multi-line
44
-
comment */
54
+
/* You can also use multi-line comments
55
+
to temporarily disable code blocks:
56
+
57
+
int debugValue = 0;
58
+
debugValue = calculateDebug();
59
+
*/
60
+
61
+
int result = /* inline comment */ calculateTotal();
62
+
63
+
```
45
64
46
-
/* multi-line
47
-
comment */ int value;
65
+
## Best practices
48
66
49
-
int value; /* multi-line
50
-
comment */ value = 0;
67
+
Use comments to:
51
68
52
-
int value; /* multi-line comment */ value = 0;
53
-
```
69
+
* Explain complex logic or business rules
70
+
* Document function parameters and return values
71
+
* Provide context data transformations
72
+
* Temporarily disable code during development
54
73
55
74
75
+
:::{tip}
76
+
Good comments explain _why_ something is done, not just _what_ is being done. The code itself should be clear enough to show what it does.
Keywords are reserved tokens for built-in language features.
14
+
Keywords are reserved tokens for built-in language features in Painless. These special words have predefined meanings and cannot be used as [identifiers](/reference/scripting-languages/painless/painless-identifiers.md), such as variable names, function names, or field names.
14
15
15
-
**Errors**
16
+
:::{important}
17
+
In Painless documentation, "keywords" refers to reserved words in the scripting language itself. They are different from the {{es}} [`keyword`](/reference/elasticsearch/mapping-reference/keyword#keyword-field-type.md) field type, which is used for exact-value searches and aggregations in your data mappings.
18
+
:::
16
19
17
-
* If a keyword is used as an [identifier](/reference/scripting-languages/painless/painless-identifiers.md).
20
+
When you write Painless scripts, keywords provide the fundamental building blocks for creating logic, defining data types, and controlling program flow. Since these words have special significance to the Painless compiler, attempting to use them for other purposes will result in compilation errors.
18
21
19
-
**Keywords**
22
+
### List of keywords:
20
23
21
-
||||||
22
-
| --- | --- | --- | --- | --- |
23
24
| if | else | while | do | for |
25
+
| :---- | :---- | :---- | :---- | :---- |
24
26
| in | continue | break | return | new |
25
27
| try | catch | throw | this | instanceof |
26
28
29
+
## Understanding keyword restrictions
30
+
31
+
Examples of restricted terms include `if`, which tells the compiler to create a conditional statement, and `int`, which declares an integer variable type.
32
+
33
+
### Examples of valid keyword usage:
34
+
35
+
```
36
+
// Keywords used correctly for their intended purpose
# Painless language specification [painless-lang-spec]
12
+
# Painless language specification (syntax) [painless-lang-spec]
12
13
13
-
Painless is a scripting language designed for security and performance. Painless syntax is similar to Java syntax along with some additional features such as dynamic typing, Map and List accessor shortcuts, and array initializers. As a direct comparison to Java, there are some important differences, especially related to the casting model. For more detailed conceptual information about the basic constructs that Painless and Java share, refer to the corresponding topics in the [Java Language Specification](https://docs.oracle.com/javase/specs/jls/se8/html/index.md).
14
+
Painless is a scripting language designed for security and performance in {{es}}.
Painless scripts are parsed and compiled using the [ANTLR4](https://www.antlr.org/) and [ASM](https://asm.ow2.org/) libraries. Scripts are compiled directly into Java Virtual Machine (JVM) byte code and executed against a standard JVM. This specification uses ANTLR4 grammar notation to describe the allowed syntax. However, the actual Painless grammar is more compact than what is shown here.
17
+
* Dynamic typing
18
+
* Map and list accessor shortcuts
19
+
* Array Initializers
20
+
* Object simplified object manipulation
16
21
17
22
23
+
Built on the Java Virtual Machine (JVM), Painless compiles directly into bytecode and runs in a controlled sandbox environment optimized for {{es}} scripting requirements.
18
24
25
+
For information about basic constructs that Painless and Java share, refer to corresponding topics in the [Java Language Specification](https://docs.oracle.com/javase/specs/jls/se8/html/index.md). However, understanding the differences in Painless is essential for effective script development.
19
26
27
+
## Compilation process
20
28
29
+
Painless scripts are parsed and compiled using the [ANTLR4](https://www.antlr.org/) and [ASM](https://asm.ow2.org/) libraries. Scripts are compiled directly into Java Virtual Machine (JVM) bytecode and executed against a standard JVM.
1.**Script input:** Painless code embedded in the JSON queries
38
+
2.**Compilation:** ANTLR4 and ASM libraries parse and compile the script into JVM bytecode
39
+
3.**Execution:** Bytecode runs on the standard Java Virtual Machine
40
+
41
+
This documentation presents the Painless language syntax in an educational format, optimized for developer understanding. The underlying grammar, however, is implemented using more concise ANTLR4 rules for efficient parsing.
24
42
43
+
## Context-aware syntax
25
44
45
+
Painless syntax availability and behavior vary by execution context, ensuring scripts are safe within their intended environment. Each context directly affects script functionality since they provide a set of variables, API restrictions, and the expected data types a script will return.
26
46
47
+
This context-aware design allows Painless to optimize performance and security for each use case. For comprehensive information about available contexts and their specific capabilities, refer to [Painless contexts](/reference/scripting-languages/painless/painless-contexts.md).
27
48
49
+
### Each context defines:
28
50
51
+
***Available variables:** Context-specific variables such as `doc`, `ctx`, `_source`, or specialized objects depending on the execution context
52
+
***API allowlist:** Permitted classes, methods, and fields from Java and {{es}} APIs
53
+
***Return type expectations:** Expected script output format and type constraints
29
54
55
+
Understanding context-syntax relationships is essential for effective Painless development. For detailed information about context-syntax patterns and practical examples, refer to [Painless syntax-context bridge](docs-content://explore-analyze/scripting/painess-syntax-context-bridge.md).
30
56
57
+
:::{image} images/painless-integration-points.png
58
+
:alt: Painless integration-points
59
+
:::
31
60
61
+
### Where to write Painless scripts:
32
62
63
+
*[**Dev tools console**](docs-content://explore-analyze/query-filter/tools/console.md)**:** Interactive script development and testing
64
+
*[**Ingest pipelines:**](docs-content://manage-data/ingest/transform-enrich/ingest-pipelines.md) Document processing during indexing
65
+
*[**Update API:**](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-update) Single and bulk document modifications
66
+
*[**Search queries:**](docs-content://solutions/search/querying-for-search.md) Custom scoring, filtering, and field generation
67
+
*[**Runtime fields:**](docs-content://manage-data/data-store/mapping/runtime-fields.md) Dynamic field computation at query time
68
+
*[**Watchers:**](docs-content://explore-analyze/alerts-cases/watcher.md) Alert conditions and notification actions
69
+
*[**Reindex API:**](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-reindex) Data transformation during index migration
70
+
*[**Aggregations:**](docs-content://explore-analyze/query-filter/aggregations.md) Custom calculations and bucket processing
33
71
72
+
Each integration point corresponds to a specific Painless context with distinct capabilities and variable access patterns.
34
73
74
+
## Technical differences from Java
75
+
76
+
Painless has implemented key differences from Java in order to optimize security and scripting performance:
77
+
78
+
***Dynamic typing with `def`:** Runtime type determination for flexible variable handling
79
+
***Enhanced collection access:** Direct syntax shortcuts for Maps (`map.key`) and Lists (`list[index]`)
80
+
***Stricter casting model:** Explicit type conversions prevent runtime errors
81
+
***Reference vs content equality:**`==` calls `.equals()`method, `===` for reference comparison
82
+
***Security restrictions:** No reflection APIs, controlled class access through allowlists
83
+
***Automatic safety controls:** Loop iteration limits and recursion prevention
84
+
85
+
These differences ensure safe execution while maintaining familiar Java-like syntax for developers.
86
+
87
+
## JavaScript in Painless
88
+
89
+
Painless integrates with Lucene’s expression language, enabling JavaScript syntax for high-performance mathematical operations and custom functions within {{es}}.
90
+
91
+
### Key capabilities:
92
+
93
+
***Performance optimization:** Compiles directly to bytecode for native execution speed
94
+
***Mathematical functions:** Access to specialized mathematical functions for scoring calculations
95
+
***Field access:** Streamlined `doc\['field'].value` syntax for document field operations
96
+
97
+
### Limitations:
98
+
99
+
* Restricted to mathematical expressions and field access operations
100
+
* No complex control flow or custom function definitions
101
+
* Limited to numeric and boolean data types
102
+
103
+
JavaScript expressions through Lucene provide a specialized, high-performance option designed specifically for custom ranking and sorting functions. For comprehensive information about Javascript expression capabilities, syntax examples, and usage patterns, refer to [Lucene Expressions Language](docs-content://explore-analyze/scripting/modules-scripting-expression.md).
0 commit comments