- Elasticsearch Guide: other versions:
- Getting Started
- Setup Elasticsearch
- Breaking changes
- Breaking changes in 5.1
- Breaking changes in 5.0
- Search and Query DSL changes
- Mapping changes
- Percolator changes
- Suggester changes
- Index APIs changes
- Document API changes
- Settings changes
- Allocation changes
- HTTP changes
- REST API changes
- CAT API changes
- Java API changes
- Packaging
- Plugin changes
- Filesystem related changes
- Path to data on disk
- Aggregation changes
- Script related changes
- API Conventions
- Document APIs
- Search APIs
- Aggregations
- Metrics Aggregations
- Avg Aggregation
- Cardinality Aggregation
- Extended Stats Aggregation
- Geo Bounds Aggregation
- Geo Centroid Aggregation
- Max Aggregation
- Min Aggregation
- Percentiles Aggregation
- Percentile Ranks Aggregation
- Scripted Metric Aggregation
- Stats Aggregation
- Sum Aggregation
- Top hits Aggregation
- Value Count Aggregation
- Bucket Aggregations
- Children Aggregation
- Date Histogram Aggregation
- Date Range Aggregation
- Diversified Sampler Aggregation
- Filter Aggregation
- Filters Aggregation
- Geo Distance Aggregation
- GeoHash grid Aggregation
- Global Aggregation
- Histogram Aggregation
- IP Range Aggregation
- Missing Aggregation
- Nested Aggregation
- Range Aggregation
- Reverse nested Aggregation
- Sampler Aggregation
- Significant Terms Aggregation
- Terms Aggregation
- Pipeline Aggregations
- Avg Bucket Aggregation
- Derivative Aggregation
- Max Bucket Aggregation
- Min Bucket Aggregation
- Sum Bucket Aggregation
- Stats Bucket Aggregation
- Extended Stats Bucket Aggregation
- Percentiles Bucket Aggregation
- Moving Average Aggregation
- Cumulative Sum Aggregation
- Bucket Script Aggregation
- Bucket Selector Aggregation
- Serial Differencing Aggregation
- Matrix Aggregations
- Caching heavy aggregations
- Returning only aggregation results
- Aggregation Metadata
- Metrics Aggregations
- Indices APIs
- Create Index
- Delete Index
- Get Index
- Indices Exists
- Open / Close Index API
- Shrink Index
- Rollover Index
- Put Mapping
- Get Mapping
- Get Field Mapping
- Types Exists
- Index Aliases
- Update Indices Settings
- Get Settings
- Analyze
- Index Templates
- Shadow replica indices
- Indices Stats
- Indices Segments
- Indices Recovery
- Indices Shard Stores
- Clear Cache
- Flush
- Refresh
- Force Merge
- cat APIs
- Cluster APIs
- Query DSL
- Mapping
- Analysis
- Anatomy of an analyzer
- Testing analyzers
- Analyzers
- Tokenizers
- Token Filters
- Standard Token Filter
- ASCII Folding Token Filter
- Length Token Filter
- Lowercase Token Filter
- Uppercase Token Filter
- NGram Token Filter
- Edge NGram Token Filter
- Porter Stem Token Filter
- Shingle Token Filter
- Stop Token Filter
- Word Delimiter Token Filter
- Stemmer Token Filter
- Stemmer Override Token Filter
- Keyword Marker Token Filter
- Keyword Repeat Token Filter
- KStem Token Filter
- Snowball Token Filter
- Phonetic Token Filter
- Synonym Token Filter
- Compound Word Token Filter
- Reverse Token Filter
- Elision Token Filter
- Truncate Token Filter
- Unique Token Filter
- Pattern Capture Token Filter
- Pattern Replace Token Filter
- Trim Token Filter
- Limit Token Count Token Filter
- Hunspell Token Filter
- Common Grams Token Filter
- Normalization Token Filter
- CJK Width Token Filter
- CJK Bigram Token Filter
- Delimited Payload Token Filter
- Keep Words Token Filter
- Keep Types Token Filter
- Classic Token Filter
- Apostrophe Token Filter
- Decimal Digit Token Filter
- Fingerprint Token Filter
- Minhash Token Filter
- Character Filters
- Modules
- Index Modules
- Ingest Node
- Pipeline Definition
- Ingest APIs
- Accessing Data in Pipelines
- Handling Failures in Pipelines
- Processors
- Append Processor
- Convert Processor
- Date Processor
- Date Index Name Processor
- Fail Processor
- Foreach Processor
- Grok Processor
- Gsub Processor
- Join Processor
- JSON Processor
- Lowercase Processor
- Remove Processor
- Rename Processor
- Script Processor
- Set Processor
- Split Processor
- Sort Processor
- Trim Processor
- Uppercase Processor
- Dot Expander Processor
- How To
- Testing
- Glossary of terms
- Release Notes
- 5.1.2 Release Notes
- 5.1.1 Release Notes
- 5.1.0 Release Notes
- 5.0.2 Release Notes
- 5.0.1 Release Notes
- 5.0.0 Combined Release Notes
- 5.0.0 GA Release Notes
- 5.0.0-rc1 Release Notes
- 5.0.0-beta1 Release Notes
- 5.0.0-alpha5 Release Notes
- 5.0.0-alpha4 Release Notes
- 5.0.0-alpha3 Release Notes
- 5.0.0-alpha2 Release Notes
- 5.0.0-alpha1 Release Notes
- 5.0.0-alpha1 Release Notes (Changes previously released in 2.x)
WARNING: Version 5.1 of Elasticsearch has passed its EOL date.
This documentation is no longer being maintained and may be removed. If you are running this version, we strongly advise you to upgrade. For the latest information, see the current release documentation.
Painless Syntax
editPainless Syntax
editThe Painless scripting language is new and is still marked as experimental. The syntax or API may be changed in the future in non-backwards compatible ways if required.
Variable types
editPainless supports all of Java’s types, including array types, but adds some additional built-in types.
Def
editThe dynamic type def
serves as a placeholder for any other type. It adopts the behavior
of whatever runtime type it represents.
String
editString constants can be declared with single quotes, to avoid escaping horrors with JSON:
def mystring = 'foo';
Arrays
editArrays can be subscripted starting from 0
for traditional array access or with
negative numbers to starting from the back of the array. So the following
returns 2
.
int[] x = new int[5]; x[0]++; x[-5]++; return x[0];
List
editLists can be created explicitly (e.g. new ArrayList()
) or initialized similar to Groovy:
def list = [1,2,3];
Lists can also be accessed similar to arrays. They support .length
and
subscripts, including negative subscripts to read from the back of the list:
def list = [1,2,3]; list[-1] = 5 return list[0]
Map
editMaps can be created explicitly (e.g. new HashMap()
) or initialized similar to Groovy:
def person = ['name': 'Joe', 'age': 63];
Map keys can also be accessed as properties.
def person = ['name': 'Joe', 'age': 63]; person.retired = true; return person.name
Map keys can also be accessed via subscript (for keys containing special characters):
return map['something-absurd!']
Pattern
editRegular expression constants are directly supported:
Pattern p = /[aeiou]/
Patterns can only be created via this mechanism. This ensures fast performance, regular expressions are always constants and compiled efficiently a single time.
Pattern flags
editYou can define flags on patterns in Painless by adding characters after the
trailing /
like /foo/i
or /foo \w #comment/iUx
. Painless exposes all the
flags from
Java’s Pattern class
using these characters:
Character | Java Constant | Example |
---|---|---|
|
CANON_EQ |
|
|
CASE_INSENSITIVE |
|
|
LITERAL |
|
|
MULTILINE |
|
|
DOTALL (aka single line) |
|
|
UNICODE_CHARACTER_CLASS |
|
|
UNICODE_CASE |
|
|
COMMENTS (aka extended) |
|
Dereferences
editLike lots of languages, Painless uses .
to reference fields and call methods:
String foo = 'foo'; TypeWithGetterOrPublicField bar = new TypeWithGetterOrPublicField() return foo.length() + bar.x
Like Groovy, Painless uses ?.
to perform null-safe references, with the
result being null
if the left hand side is null:
String foo = null; return foo?.length() // Returns null
Unlike Groovy, Painless doesn’t support writing to null values with this operator:
TypeWithSetterOrPublicField foo = null; foo?.x = 'bar' // Compile error
Operators
editAll of Java’s operators are supported with the same precedence, promotion, and semantics.
There are only a few minor differences and add-ons:
-
==
behaves as Java’s for numeric types, but for non-numeric types acts asObject.equals()
-
===
and!==
support exact reference comparison (e.g.x === y
) -
=~
true if a portion of the text matches a pattern (e.g.x =~ /b/
) -
==~
true if the entire text matches a pattern (e.g.x ==~ /[Bb]ob/
)
The ?:
(aka Elvis) operator coalesces null values. So x ?: 0
is 0
if x
is null
and whatever value x
has otherwise. It is a convenient way to write
default values like doc['x'].value ?: 0
which is 0 if x
is not in the
document being processed. It can also work with null safe dereferences to
efficiently handle null in chains. For example,
doc['foo.keyword'].value?.length() ?: 0
is 0 if the document being processed
doesn’t have a foo.keyword
field but is the length of that field if it does.
Lastly, ?:
is lazy so the right hand side is not evaluated at all if the left
hand side isn’t null.
Unlike Groovy, Painless' ?:
operator only coalesces null
, not false
or falsy values. Strictly
speaking Painless' ?:
is more like Kotlin’s ?:
than Groovy’s ?:
.
The result of ?.
and ?:
can’t be assigned to primitives. So
int[] someArray = null; int l = someArray?.length
and
int s = params.size ?: 100
don’t work. Do
def someArray = null; def l = someArray?.length
and
def s = params.size ?: 100
instead.
Control flow
editJava’s control flow statements are supported, with the exception
of the switch
statement.
In addition to Java’s enhanced for
loop, the for in
syntax from groovy can also be used:
for (item : list) { ... }
Functions
editFunctions can be declared at the beginning of the script, for example:
boolean isNegative(def x) { x < 0 } ... if (isNegative(someVar)) { ... }
Lambda expressions
editLambda expressions and method references work the same as Java’s.
list.removeIf(item -> item == 2); list.removeIf((int item) -> item == 2); list.removeIf((int item) -> { item == 2 }); list.sort((x, y) -> x - y); list.sort(Integer::compare);
Method references to functions within the script can be accomplished using this
, e.g. list.sort(this::mycompare)
.
On this page