From c01029875a091076ed42cdb3a41c10b1a9a5a20f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Istv=C3=A1n=20Zolt=C3=A1n=20Szab=C3=B3?= Date: Tue, 23 May 2023 16:32:31 +0200 Subject: [PATCH] [DOCS] Adds example of using stored scripts in Transforms (#96285) (#96294) --- .../transform/painless-examples.asciidoc | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/docs/reference/transform/painless-examples.asciidoc b/docs/reference/transform/painless-examples.asciidoc index 8f8048694bf57..8eb50964f4d5b 100644 --- a/docs/reference/transform/painless-examples.asciidoc +++ b/docs/reference/transform/painless-examples.asciidoc @@ -107,6 +107,101 @@ You can retrieve the last value in a similar way: -------------------------------------------------- // NOTCONSOLE + +[discrete] +[[top-hits-stored-scripts]] +=== Getting top hits by using stored scripts + +You can also use the power of +{ref}/create-stored-script-api.html[stored scripts] to get the latest value. +Stored scripts reduce compilation time, make searches faster, and are +updatable. + +1. Create the stored scripts: ++ +-- +[source,js] +-------------------------------------------------- +POST _scripts/last-value-map-init +{ + "script": { + "lang": "painless", + "source": """ + state.timestamp_latest = 0L; state.last_value = '' + """ + } +} + +POST _scripts/last-value-map +{ + "script": { + "lang": "painless", + "source": """ + def current_date = doc['@timestamp'].getValue().toInstant().toEpochMilli(); + if (current_date > state.timestamp_latest) + {state.timestamp_latest = current_date; + state.last_value = doc[params['key']].value;} + """ + } +} + +POST _scripts/last-value-combine +{ + "script": { + "lang": "painless", + "source": """ + return state + """ + } +} + +POST _scripts/last-value-reduce +{ + "script": { + "lang": "painless", + "source": """ + def last_value = ''; + def timestamp_latest = 0L; + for (s in states) {if (s.timestamp_latest > (timestamp_latest)) + {timestamp_latest = s.timestamp_latest; last_value = s.last_value;}} + return last_value + """ + } +} +-------------------------------------------------- +// NOTCONSOLE +-- + +2. Use the stored scripts in a scripted metric aggregation. ++ +-- +[source,js] +-------------------------------------------------- +"aggregations":{ + "latest_value":{ + "scripted_metric":{ + "init_script":{ + "id":"last-value-map-init" + }, + "map_script":{ + "id":"last-value-map", + "params":{ + "key":"field_with_last_value" <1> + } + }, + "combine_script":{ + "id":"last-value-combine" + }, + "reduce_script":{ + "id":"last-value-reduce" + } +-------------------------------------------------- +// NOTCONSOLE +<1> The parameter `field_with_last_value` can be set any field that you want the +latest value for. +-- + + [[painless-time-features]] == Getting time features by using aggregations