Skip to content

Commit

Permalink
[DOCS] Adds example of using stored scripts in Transforms (#96285) (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
szabosteve authored May 23, 2023
1 parent 7ce3adf commit c010298
Showing 1 changed file with 95 additions and 0 deletions.
95 changes: 95 additions & 0 deletions docs/reference/transform/painless-examples.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit c010298

Please sign in to comment.