@@ -107,6 +107,101 @@ You can retrieve the last value in a similar way:
107
107
--------------------------------------------------
108
108
// NOTCONSOLE
109
109
110
+
111
+ [discrete]
112
+ [[top-hits-stored-scripts]]
113
+ === Getting top hits by using stored scripts
114
+
115
+ You can also use the power of
116
+ {ref}/create-stored-script-api.html[stored scripts] to get the latest value.
117
+ Stored scripts reduce compilation time, make searches faster, and are
118
+ updatable.
119
+
120
+ 1. Create the stored scripts:
121
+ +
122
+ --
123
+ [source,js]
124
+ --------------------------------------------------
125
+ POST _scripts/last-value-map-init
126
+ {
127
+ "script": {
128
+ "lang": "painless",
129
+ "source": """
130
+ state.timestamp_latest = 0L; state.last_value = ''
131
+ """
132
+ }
133
+ }
134
+
135
+ POST _scripts/last-value-map
136
+ {
137
+ "script": {
138
+ "lang": "painless",
139
+ "source": """
140
+ def current_date = doc['@timestamp'].getValue().toInstant().toEpochMilli();
141
+ if (current_date > state.timestamp_latest)
142
+ {state.timestamp_latest = current_date;
143
+ state.last_value = doc[params['key']].value;}
144
+ """
145
+ }
146
+ }
147
+
148
+ POST _scripts/last-value-combine
149
+ {
150
+ "script": {
151
+ "lang": "painless",
152
+ "source": """
153
+ return state
154
+ """
155
+ }
156
+ }
157
+
158
+ POST _scripts/last-value-reduce
159
+ {
160
+ "script": {
161
+ "lang": "painless",
162
+ "source": """
163
+ def last_value = '';
164
+ def timestamp_latest = 0L;
165
+ for (s in states) {if (s.timestamp_latest > (timestamp_latest))
166
+ {timestamp_latest = s.timestamp_latest; last_value = s.last_value;}}
167
+ return last_value
168
+ """
169
+ }
170
+ }
171
+ --------------------------------------------------
172
+ // NOTCONSOLE
173
+ --
174
+
175
+ 2. Use the stored scripts in a scripted metric aggregation.
176
+ +
177
+ --
178
+ [source,js]
179
+ --------------------------------------------------
180
+ "aggregations":{
181
+ "latest_value":{
182
+ "scripted_metric":{
183
+ "init_script":{
184
+ "id":"last-value-map-init"
185
+ },
186
+ "map_script":{
187
+ "id":"last-value-map",
188
+ "params":{
189
+ "key":"field_with_last_value" <1>
190
+ }
191
+ },
192
+ "combine_script":{
193
+ "id":"last-value-combine"
194
+ },
195
+ "reduce_script":{
196
+ "id":"last-value-reduce"
197
+ }
198
+ --------------------------------------------------
199
+ // NOTCONSOLE
200
+ <1> The parameter `field_with_last_value` can be set any field that you want the
201
+ latest value for.
202
+ --
203
+
204
+
110
205
[[painless-time-features]]
111
206
== Getting time features by using aggregations
112
207
0 commit comments