Using JavaScript in Elasticsearch
editUsing JavaScript in Elasticsearch
editOnce the plugin has been installed, JavaScript can be used at a scripting
language by setting the lang
parameter to javascript
or js
.
Scripting is available in many APIs, but we will use an example with the
function_score
for demonstration purposes:
Inline scripts
editEnabling inline scripting on an unprotected Elasticsearch cluster is dangerous. See File scripts for a safer option.
If you have enabled inline scripts, you can use JavaScript as follows:
DELETE test PUT test/doc/1 { "num": 1.0 } PUT test/doc/2 { "num": 2.0 } GET test/_search { "query": { "function_score": { "script_score": { "script": { "inline": "doc[\"num\"].value * factor", "lang": "javascript", "params": { "factor": 2 } } } } } }
Indexed scripts
editEnabling indexed scripting on an unprotected Elasticsearch cluster is dangerous. See File scripts for a safer option.
If you have enabled indexed scripts, you can use JavaScript as follows:
DELETE test PUT test/doc/1 { "num": 1.0 } PUT test/doc/2 { "num": 2.0 } POST _scripts/javascript/my_script { "script": "doc[\"num\"].value * factor" } GET test/_search { "query": { "function_score": { "script_score": { "script": { "id": "my_script", "lang": "javascript", "params": { "factor": 2 } } } } } }
We index the script under the id |
|
The function score query retrieves the script with id |
File scripts
editYou can save your scripts to a file in the config/scripts/
directory on
every node. The .javascript
file suffix identifies the script as containing
JavaScript:
First, save this file as config/scripts/my_script.javascript
on every node
in the cluster:
doc["num"].value * factor
then use the script as follows: