painless-examples.asciidoc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. [role="xpack"]
  2. [testenv="basic"]
  3. [[transform-painless-examples]]
  4. === Painless examples for {transforms}
  5. ++++
  6. <titleabbrev>Painless examples for {transforms}</titleabbrev>
  7. ++++
  8. These examples demonstrate how to use Painless in {transforms}. You can learn
  9. more about the Painless scripting language in the
  10. {painless}/painless-guide.html[Painless guide].
  11. * <<painless-top-hits>>
  12. * <<painless-time-features>>
  13. * <<painless-group-by>>
  14. * <<painless-bucket-script>>
  15. * <<painless-count-http>>
  16. * <<painless-compare>>
  17. NOTE: While the context of the following examples is the {transform} use case,
  18. the Painless scripts in the snippets below can be used in other {es} search
  19. aggregations, too.
  20. [discrete]
  21. [[painless-top-hits]]
  22. ==== Getting top hits by using scripted metric aggregation
  23. This snippet shows how to find the latest document, in other words the document
  24. with the earliest timestamp. From a technical perspective, it helps to achieve
  25. the function of a <<search-aggregations-metrics-top-hits-aggregation>> by using
  26. scripted metric aggregation in a {transform}, which provides a metric output.
  27. [source,js]
  28. --------------------------------------------------
  29. "aggregations": {
  30. "latest_doc": {
  31. "scripted_metric": {
  32. "init_script": "state.timestamp_latest = 0L; state.last_doc = ''", <1>
  33. "map_script": """ <2>
  34. def current_date = doc['@timestamp'].getValue().toInstant().toEpochMilli();
  35. if (current_date > state.timestamp_latest)
  36. {state.timestamp_latest = current_date;
  37. state.last_doc = new HashMap(params['_source']);}
  38. """,
  39. "combine_script": "return state", <3>
  40. "reduce_script": """ <4>
  41. def last_doc = '';
  42. def timestamp_latest = 0L;
  43. for (s in states) {if (s.timestamp_latest > (timestamp_latest))
  44. {timestamp_latest = s.timestamp_latest; last_doc = s.last_doc;}}
  45. return last_doc
  46. """
  47. }
  48. }
  49. }
  50. --------------------------------------------------
  51. // NOTCONSOLE
  52. <1> The `init_script` creates a long type `timestamp_latest` and a string type
  53. `last_doc` in the `state` object.
  54. <2> The `map_script` defines `current_date` based on the timestamp of the
  55. document, then compares `current_date` with `state.timestamp_latest`, finally
  56. returns `state.last_doc` from the shard. By using `new HashMap(...)` you copy
  57. the source document, this is important whenever you want to pass the full source
  58. object from one phase to the next.
  59. <3> The `combine_script` returns `state` from each shard.
  60. <4> The `reduce_script` iterates through the value of `s.timestamp_latest`
  61. returned by each shard and returns the document with the latest timestamp
  62. (`last_doc`). In the response, the top hit (in other words, the `latest_doc`) is
  63. nested below the `latest_doc` field.
  64. Check the
  65. <<scripted-metric-aggregation-scope,scope of scripts>>
  66. for detailed explanation on the respective scripts.
  67. You can retrieve the last value in a similar way:
  68. [source,js]
  69. --------------------------------------------------
  70. "aggregations": {
  71. "latest_value": {
  72. "scripted_metric": {
  73. "init_script": "state.timestamp_latest = 0L; state.last_value = ''",
  74. "map_script": """
  75. def current_date = doc['date'].getValue().toInstant().toEpochMilli();
  76. if (current_date > state.timestamp_latest)
  77. {state.timestamp_latest = current_date;
  78. state.last_value = params['_source']['value'];}
  79. """,
  80. "combine_script": "return state",
  81. "reduce_script": """
  82. def last_value = '';
  83. def timestamp_latest = 0L;
  84. for (s in states) {if (s.timestamp_latest > (timestamp_latest))
  85. {timestamp_latest = s.timestamp_latest; last_value = s.last_value;}}
  86. return last_value
  87. """
  88. }
  89. }
  90. }
  91. --------------------------------------------------
  92. // NOTCONSOLE
  93. [discrete]
  94. [[painless-time-features]]
  95. ==== Getting time features as scripted fields
  96. This snippet shows how to extract time based features by using Painless in a
  97. {transform}. The snippet uses an index where `@timestamp` is defined as a `date`
  98. type field.
  99. [source,js]
  100. --------------------------------------------------
  101. "aggregations": {
  102. "script_fields": {
  103. "hour_of_day": { <1>
  104. "script": {
  105. "lang": "painless",
  106. "source": """
  107. ZonedDateTime date = doc['@timestamp'].value; <2>
  108. return date.getHour(); <3>
  109. """
  110. }
  111. },
  112. "month_of_year": { <4>
  113. "script": {
  114. "lang": "painless",
  115. "source": """
  116. ZonedDateTime date = doc['@timestamp'].value; <5>
  117. return date.getMonthValue(); <6>
  118. """
  119. }
  120. }
  121. },
  122. ...
  123. }
  124. --------------------------------------------------
  125. // NOTCONSOLE
  126. <1> Contains the Painless script that returns the hour of the day.
  127. <2> Sets `date` based on the timestamp of the document.
  128. <3> Returns the hour value from `date`.
  129. <4> Contains the Painless script that returns the month of the year.
  130. <5> Sets `date` based on the timestamp of the document.
  131. <6> Returns the month value from `date`.
  132. [discrete]
  133. [[painless-group-by]]
  134. ==== Using Painless in `group_by`
  135. It is possible to base the `group_by` property of a {transform} on the output of
  136. a script. The following example uses the {kib} sample web logs dataset. The goal
  137. here is to make the {transform} output easier to understand through normalizing
  138. the value of the fields that the data is grouped by.
  139. [source,console]
  140. --------------------------------------------------
  141. POST _transform/_preview
  142. {
  143. "source": {
  144. "index": [ <1>
  145. "kibana_sample_data_logs"
  146. ]
  147. },
  148. "pivot": {
  149. "group_by": {
  150. "agent": {
  151. "terms": {
  152. "script": { <2>
  153. "source": """String agent = doc['agent.keyword'].value;
  154. if (agent.contains("MSIE")) {
  155. return "internet explorer";
  156. } else if (agent.contains("AppleWebKit")) {
  157. return "safari";
  158. } else if (agent.contains('Firefox')) {
  159. return "firefox";
  160. } else { return agent }""",
  161. "lang": "painless"
  162. }
  163. }
  164. }
  165. },
  166. "aggregations": { <3>
  167. "200": {
  168. "filter": {
  169. "term": {
  170. "response": "200"
  171. }
  172. }
  173. },
  174. "404": {
  175. "filter": {
  176. "term": {
  177. "response": "404"
  178. }
  179. }
  180. },
  181. "503": {
  182. "filter": {
  183. "term": {
  184. "response": "503"
  185. }
  186. }
  187. }
  188. }
  189. },
  190. "dest": { <4>
  191. "index": "pivot_logs"
  192. }
  193. }
  194. --------------------------------------------------
  195. // TEST[skip:setup kibana sample data]
  196. <1> Specifies the source index or indices.
  197. <2> The script defines an `agent` string based on the `agent` field of the
  198. documents, then iterates through the values. If an `agent` field contains
  199. "MSIE", than the script returns "Internet Explorer". If it contains
  200. `AppleWebKit`, it returns "safari". It returns "firefox" if the field value
  201. contains "Firefox". Finally, in every other case, the value of the field is
  202. returned.
  203. <3> The aggregations object contains filters that narrow down the results to
  204. documents that contains `200`, `404`, or `503` values in the `response` field.
  205. <4> Specifies the destination index of the {transform}.
  206. The API returns the following result:
  207. [source,js]
  208. --------------------------------------------------
  209. {
  210. "preview" : [
  211. {
  212. "agent" : "firefox",
  213. "200" : 4931,
  214. "404" : 259,
  215. "503" : 172
  216. },
  217. {
  218. "agent" : "internet explorer",
  219. "200" : 3674,
  220. "404" : 210,
  221. "503" : 126
  222. },
  223. {
  224. "agent" : "safari",
  225. "200" : 4227,
  226. "404" : 332,
  227. "503" : 143
  228. }
  229. ],
  230. "mappings" : {
  231. "properties" : {
  232. "200" : {
  233. "type" : "long"
  234. },
  235. "agent" : {
  236. "type" : "keyword"
  237. },
  238. "404" : {
  239. "type" : "long"
  240. },
  241. "503" : {
  242. "type" : "long"
  243. }
  244. }
  245. }
  246. }
  247. --------------------------------------------------
  248. // NOTCONSOLE
  249. You can see that the `agent` values are simplified so it is easier to interpret
  250. them. The table below shows how normalization modifies the output of the
  251. {transform} in our example compared to the non-normalized values.
  252. [width="50%"]
  253. |===
  254. | Non-normalized `agent` value | Normalized `agent` value
  255. | "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)" | "internet explorer"
  256. | "Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.50 Safari/534.24" | "safari"
  257. | "Mozilla/5.0 (X11; Linux x86_64; rv:6.0a1) Gecko/20110421 Firefox/6.0a1" | "firefox"
  258. |===
  259. [discrete]
  260. [[painless-bucket-script]]
  261. ==== Getting duration by using bucket script
  262. This example shows you how to get the duration of a session by client IP from a
  263. data log by using
  264. {ref}/search-aggregations-pipeline-bucket-script-aggregation.html[bucket script].
  265. The example uses the {kib} sample web logs dataset.
  266. [source,console]
  267. --------------------------------------------------
  268. PUT _data_frame/transforms/data_log
  269. {
  270. "source": {
  271. "index": "kibana_sample_data_logs"
  272. },
  273. "dest": {
  274. "index": "data-logs-by-client"
  275. },
  276. "pivot": {
  277. "group_by": {
  278. "machine.os": {"terms": {"field": "machine.os.keyword"}},
  279. "machine.ip": {"terms": {"field": "clientip"}}
  280. },
  281. "aggregations": {
  282. "time_frame.lte": {
  283. "max": {
  284. "field": "timestamp"
  285. }
  286. },
  287. "time_frame.gte": {
  288. "min": {
  289. "field": "timestamp"
  290. }
  291. },
  292. "time_length": { <1>
  293. "bucket_script": {
  294. "buckets_path": { <2>
  295. "min": "time_frame.gte.value",
  296. "max": "time_frame.lte.value"
  297. },
  298. "script": "params.max - params.min" <3>
  299. }
  300. }
  301. }
  302. }
  303. }
  304. --------------------------------------------------
  305. // TEST[skip:setup kibana sample data]
  306. <1> To define the length of the sessions, we use a bucket script.
  307. <2> The bucket path is a map of script variables and their associated path to
  308. the buckets you want to use for the variable. In this particular case, `min` and
  309. `max` are variables mapped to `time_frame.gte.value` and `time_frame.lte.value`.
  310. <3> Finally, the script substracts the start date of the session from the end
  311. date which results in the duration of the session.
  312. [discrete]
  313. [[painless-count-http]]
  314. ==== Counting HTTP responses by using scripted metric aggregation
  315. You can count the different HTTP response types in a web log data set by using
  316. scripted metric aggregation as part of the {transform}. The example below
  317. assumes that the HTTP response codes are stored as keywords in the `response`
  318. field of the documents.
  319. [source,js]
  320. --------------------------------------------------
  321. "aggregations": { <1>
  322. "responses.counts": { <2>
  323. "scripted_metric": { <3>
  324. "init_script": "state.responses = ['error':0L,'success':0L,'other':0L]", <4>
  325. "map_script": """ <5>
  326. def code = doc['response.keyword'].value;
  327. if (code.startsWith('5') || code.startsWith('4')) {
  328. state.responses.error += 1 ;
  329. } else if(code.startsWith('2')) {
  330. state.responses.success += 1;
  331. } else {
  332. state.responses.other += 1;
  333. }
  334. """,
  335. "combine_script": "state.responses", <6>
  336. "reduce_script": """ <7>
  337. def counts = ['error': 0L, 'success': 0L, 'other': 0L];
  338. for (responses in states) {
  339. counts.error += responses['error'];
  340. counts.success += responses['success'];
  341. counts.other += responses['other'];
  342. }
  343. return counts;
  344. """
  345. }
  346. },
  347. ...
  348. }
  349. --------------------------------------------------
  350. // NOTCONSOLE
  351. <1> The `aggregations` object of the {transform} that contains all aggregations.
  352. <2> Object of the `scripted_metric` aggregation.
  353. <3> This `scripted_metric` performs a distributed operation on the web log data
  354. to count specific types of HTTP responses (error, success, and other).
  355. <4> The `init_script` creates a `responses` array in the `state` object with
  356. three properties (`error`, `success`, `other`) with long data type.
  357. <5> The `map_script` defines `code` based on the `response.keyword` value of the
  358. document, then it counts the errors, successes, and other responses based on the
  359. first digit of the responses.
  360. <6> The `combine_script` returns `state.responses` from each shard.
  361. <7> The `reduce_script` creates a `counts` array with the `error`, `success`,
  362. and `other` properties, then iterates through the value of `responses` returned
  363. by each shard and assigns the different response types to the appropriate
  364. properties of the `counts` object; error responses to the error counts, success
  365. responses to the success counts, and other responses to the other counts.
  366. Finally, returns the `counts` array with the response counts.
  367. [discrete]
  368. [[painless-compare]]
  369. ==== Comparing indices by using scripted metric aggregations
  370. This example shows how to compare the content of two indices by a {transform}
  371. that uses a scripted metric aggregation.
  372. [source,console]
  373. --------------------------------------------------
  374. POST _transform/_preview
  375. {
  376. "id" : "index_compare",
  377. "source" : { <1>
  378. "index" : [
  379. "index1",
  380. "index2"
  381. ],
  382. "query" : {
  383. "match_all" : { }
  384. }
  385. },
  386. "dest" : { <2>
  387. "index" : "compare"
  388. },
  389. "pivot" : {
  390. "group_by" : {
  391. "unique-id" : {
  392. "terms" : {
  393. "field" : "<unique-id-field>" <3>
  394. }
  395. }
  396. },
  397. "aggregations" : {
  398. "compare" : { <4>
  399. "scripted_metric" : {
  400. "init_script" : "",
  401. "map_script" : "state.doc = new HashMap(params['_source'])", <5>
  402. "combine_script" : "return state", <6>
  403. "reduce_script" : """ <7>
  404. if (states.size() != 2) {
  405. return "count_mismatch"
  406. }
  407. if (states.get(0).equals(states.get(1))) {
  408. return "match"
  409. } else {
  410. return "mismatch"
  411. }
  412. """
  413. }
  414. }
  415. }
  416. }
  417. }
  418. --------------------------------------------------
  419. // TEST[skip:setup kibana sample data]
  420. <1> The indices referenced in the `source` object are compared to each other.
  421. <2> The `dest` index contains the results of the comparison.
  422. <3> The `group_by` field needs to be a unique identifier for each document.
  423. <4> Object of the `scripted_metric` aggregation.
  424. <5> The `map_script` defines `doc` in the state object. By using
  425. `new HashMap(...)` you copy the source document, this is important whenever you
  426. want to pass the full source object from one phase to the next.
  427. <6> The `combine_script` returns `state` from each shard.
  428. <7> The `reduce_script` checks if the size of the indices are equal. If they are
  429. not equal, than it reports back a `count_mismatch`. Then it iterates through all
  430. the values of the two indices and compare them. If the values are equal, then it
  431. returns a `match`, otherwise returns a `mismatch`.