Browse Source

[DOCS] Adds example of using stored scripts in Transforms (#96285)

István Zoltán Szabó 2 years ago
parent
commit
ff5c86eb7c
1 changed files with 95 additions and 0 deletions
  1. 95 0
      docs/reference/transform/painless-examples.asciidoc

+ 95 - 0
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