Elasticsearch allows us to define complex expressions that can be used to return a new calculated field value.
These special fields are called script_fields
, and they can be expressed with a script in every available Elasticsearch scripting language.
You need an up-and-running Elasticsearch installation as we described the Downloading and installing Elasticsearch recipe in Chapter 2, Downloading and Setup.
To execute curl
via the command-line you need to install curl
for your operating system.
To correctly execute the following commands, you need an index populated with the script chapter_09/populate_for_scripting.sh
script available in the online code.
For computing return fields with scripting, we will perform the following steps:
"my_calc_field"
: This concatenates the texts of the "name"
and "description"
fields
"my_calc_field2"
: This multiplies the "price"
value by the "discount"
parameter
curl -XGET 'http://127.0.0.1:9200/test-index/test-type/_search?
pretty&size=3' -d '{
"query": {
"match_all": {}
},
"script_fields": {
"my_calc_field": {
"script": {
"inline": "params._source.name + " -- " +
params._source.description"
}
},
"my_calc_field2": {
"script": {
"inline": "doc["price"].value * params.discount",
"params": {
"discount": 0.8
}
}
}
}
}'
{ "took": 95, "timed_out": false, "_shards": ... truncated ..., "hits": { "total": 1000, "max_score": 1, "hits": [ { ... truncated ... "_id": "705", "fields": { "my_calc_field": [ "Nimrod -- amet architecto ... truncated ..." ], "my_calc_field2": [ 18.594456481933594 ] } }, { ... truncated ... "_id": "708", "fields": { "my_calc_field": [ "Sunstreak -- alias minus ... truncated ..." ], "my_calc_field2": [ 28.051638793945315 ] } }, { ... truncated ... "_id": "712", "fields": { "my_calc_field": [ "Brant, Betty -- soluta praesentium ... truncated ..." ], "my_calc_field2": [ 56.00410766601563 ] } } ] } }
The script fields are similar to executing an SQL function on a field during a select.
In Elasticsearch, after a search phase is executed and hits to be returned are calculated, if some fields (standard or script) are defined, they are calculated and returned.
The script field, which can be defined with all supported languages, is processed by passing a value to the source of the document and, if some other parameters are defined in the script (in the example discount factor), they are passed to the script function.
The script function is a code snippet, so it can contain everything that the language allows to be written, but it must be evaluated to a value (or a list of values).
18.118.210.104