Elasticsearch Scripting
Languages
- Painless *
- Expression
- Mustache
- Java
Use cases
- Query using custom condition
- Return custom field
- Update field with custom value
Query with custom condition
POST /_search
{
"query": {
"script" : {
"script" : {
"inline": "doc['value'].value > 1"
}
}
}
}
Return custom field
GET /_search
{
"script_fields": {
"square_root_field": {
"script": {
"inline": "return Math.sqrt(doc['value'].value);"
}
}
}
}
Update field with custom value
POST /_update
{
"script": "ctx._source.date='2018-03-22T06:01:47+0000'"
}
Get field
- doc['simple_field']
- params['_source']['field_1']['field_2']
- ctx['_source']['field_1']['field_2']
doc['simple_field']
- Can be used in Search and Aggregation script
- Only can be used with simple field
- Fast
- Use more memory
params['_source']['field_1']['field_2']
- Can be used in Search and Aggregation script
- Only can be used any field
- Very slow
ctx['_source']['field_1']['field_2']
- Can be used in Update script
- Only can be used any field
Tips
- We can create complex script using function, if/else, loop
- We can store script to re-use
- Use heredoc <<< in to write script in php
Complex JAVA Script
GET /_search
{
"script_fields": {
"square_root_field": {
"script": {
"inline": "
int totalScore(def scores) {
def total = 0;
for (def score : scores) {
total += score;
}
return total;
}
if (totalScore(doc['scores']) > 90) {
return 'passed';
} else {
return 'failed';
};
"
}
}
}
}
Store Script
POST _scripts/calculate-score
{
"script": {
"lang": "painless",
"source": "Math.log(_score * 2) + params.my_modifier"
}
}
GET _scripts/calculate-score
DELETE _scripts/calculate-score
heredoc
public $script = <<<JAVA
if (doc['age'] > 18) {
return 'old';
} else {
return 'young';
}
JAVA;
References
- https://www.compose.com/articles/how-to-script-painless-ly-in-elasticsearch/
Elasticsearch Scripting
By Tiến Võ Xuân
Elasticsearch Scripting
- 909