Skip to content

Commit 5ac1b57

Browse files
committed
some of the specs
1 parent e9d7f4b commit 5ac1b57

File tree

6 files changed

+212
-98
lines changed

6 files changed

+212
-98
lines changed
108 KB
Loading
444 KB
Loading

docs/reference/scripting-languages/painless/painless-comments.md

Lines changed: 48 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -10,46 +10,68 @@ products:
1010

1111
# Comments [painless-comments]
1212

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.
1414

15-
**Grammar**
15+
Painless supports two types of comments: single-line comments and multi-line comments.
1616

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+
```
1824
SINGLE_LINE_COMMENT: '//' .*? [\n\r];
19-
MULTI_LINE_COMMENT: '/*' .*? '*/';
2025
```
2126

22-
**Examples**
27+
### Example
2328

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+
```
2534

26-
```painless
27-
// single-line comment
35+
## Multi-line comments
2836

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.
3138

32-
* Multi-line comments.
39+
### Grammar
3340

34-
```painless
35-
/* multi-
36-
line
37-
comment */
41+
```
42+
MULTI_LINE_COMMENT: '/*' .*? '*/';
43+
```
3844

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;
4253
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+
```
4564

46-
/* multi-line
47-
comment */ int value;
65+
## Best practices
4866

49-
int value; /* multi-line
50-
comment */ value = 0;
67+
Use comments to:
5168

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
5473

5574

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.
77+
:::
Lines changed: 43 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
---
2+
navigation_title: Keywords
23
mapped_pages:
34
- https://www.elastic.co/guide/en/elasticsearch/painless/current/painless-keywords.html
45
applies_to:
@@ -8,19 +9,54 @@ products:
89
- id: painless
910
---
1011

11-
# Keywords [painless-keywords]
12+
# Keywords (reserved terms) [painless-keywords]
1213

13-
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.
1415

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+
:::
1619

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.
1821

19-
**Keywords**
22+
### List of keywords:
2023

21-
| | | | | |
22-
| --- | --- | --- | --- | --- |
2324
| if | else | while | do | for |
25+
| :---- | :---- | :---- | :---- | :---- |
2426
| in | continue | break | return | new |
2527
| try | catch | throw | this | instanceof |
2628

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
37+
int count = 0; // `int' declares integer type
38+
boolean isActive = true; // 'boolean' declares boolean type, 'true' is literal
39+
if (count > 0) { // 'if' creates conditional logic
40+
return count; // 'return' exits with value
41+
}
42+
43+
```
44+
45+
### Errors
46+
47+
If a keyword is used as an identifier. Painless will generate a compilation error:
48+
49+
```
50+
// These will cause compilation errors
51+
int if = 10; // Cannot use 'if' as variable name
52+
String return = "value"; // Cannot use 'return' as variable name
53+
boolean int = false; // Cannot use 'int' as variable name
54+
55+
// Use descriptive names instead
56+
int count = 10;
57+
String result = "value";
58+
boolean isEnabled = false;
59+
60+
```
61+
62+
These restrictions ensure that your scripts remain readable and that the Painless compiler can correctly parse your code without ambiguity.
Lines changed: 72 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
---
2+
navigation_title: Painless language specification
23
mapped_pages:
34
- https://www.elastic.co/guide/en/elasticsearch/painless/current/painless-lang-spec.html
45
applies_to:
@@ -8,27 +9,95 @@ products:
89
- id: painless
910
---
1011

11-
# Painless language specification [painless-lang-spec]
12+
# Painless language specification (syntax) [painless-lang-spec]
1213

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}}.
15+
Painless syntax closely resembles Java syntax while providing additional scripting-focused features:
1416

15-
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
1621

1722

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.
1824

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.
1926

27+
## Compilation process
2028

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.
2130

31+
:::{image} images/painless-compilation-process.png
32+
:alt: Painless compilation process
33+
:::
2234

35+
### Step breakdown:
2336

37+
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.
2442

43+
## Context-aware syntax
2544

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.
2646

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).
2748

49+
### Each context defines:
2850

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
2954

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).
3056

57+
:::{image} images/painless-integration-points.png
58+
:alt: Painless integration-points
59+
:::
3160

61+
### Where to write Painless scripts:
3262

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
3371

72+
Each integration point corresponds to a specific Painless context with distinct capabilities and variable access patterns.
3473

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

Comments
 (0)