painless-examples.asciidoc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  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. * <<painless-web-session>>
  18. NOTE: While the context of the following examples is the {transform} use case,
  19. the Painless scripts in the snippets below can be used in other {es} search
  20. aggregations, too.
  21. [discrete]
  22. [[painless-top-hits]]
  23. ==== Getting top hits by using scripted metric aggregation
  24. This snippet shows how to find the latest document, in other words the document
  25. with the earliest timestamp. From a technical perspective, it helps to achieve
  26. the function of a <<search-aggregations-metrics-top-hits-aggregation>> by using
  27. scripted metric aggregation in a {transform}, which provides a metric output.
  28. [source,js]
  29. --------------------------------------------------
  30. "aggregations": {
  31. "latest_doc": {
  32. "scripted_metric": {
  33. "init_script": "state.timestamp_latest = 0L; state.last_doc = ''", <1>
  34. "map_script": """ <2>
  35. def current_date = doc['@timestamp'].getValue().toInstant().toEpochMilli();
  36. if (current_date > state.timestamp_latest)
  37. {state.timestamp_latest = current_date;
  38. state.last_doc = new HashMap(params['_source']);}
  39. """,
  40. "combine_script": "return state", <3>
  41. "reduce_script": """ <4>
  42. def last_doc = '';
  43. def timestamp_latest = 0L;
  44. for (s in states) {if (s.timestamp_latest > (timestamp_latest))
  45. {timestamp_latest = s.timestamp_latest; last_doc = s.last_doc;}}
  46. return last_doc
  47. """
  48. }
  49. }
  50. }
  51. --------------------------------------------------
  52. // NOTCONSOLE
  53. <1> The `init_script` creates a long type `timestamp_latest` and a string type
  54. `last_doc` in the `state` object.
  55. <2> The `map_script` defines `current_date` based on the timestamp of the
  56. document, then compares `current_date` with `state.timestamp_latest`, finally
  57. returns `state.last_doc` from the shard. By using `new HashMap(...)` you copy
  58. the source document, this is important whenever you want to pass the full source
  59. object from one phase to the next.
  60. <3> The `combine_script` returns `state` from each shard.
  61. <4> The `reduce_script` iterates through the value of `s.timestamp_latest`
  62. returned by each shard and returns the document with the latest timestamp
  63. (`last_doc`). In the response, the top hit (in other words, the `latest_doc`) is
  64. nested below the `latest_doc` field.
  65. Check the
  66. <<scripted-metric-aggregation-scope,scope of scripts>>
  67. for detailed explanation on the respective scripts.
  68. You can retrieve the last value in a similar way:
  69. [source,js]
  70. --------------------------------------------------
  71. "aggregations": {
  72. "latest_value": {
  73. "scripted_metric": {
  74. "init_script": "state.timestamp_latest = 0L; state.last_value = ''",
  75. "map_script": """
  76. def current_date = doc['date'].getValue().toInstant().toEpochMilli();
  77. if (current_date > state.timestamp_latest)
  78. {state.timestamp_latest = current_date;
  79. state.last_value = params['_source']['value'];}
  80. """,
  81. "combine_script": "return state",
  82. "reduce_script": """
  83. def last_value = '';
  84. def timestamp_latest = 0L;
  85. for (s in states) {if (s.timestamp_latest > (timestamp_latest))
  86. {timestamp_latest = s.timestamp_latest; last_value = s.last_value;}}
  87. return last_value
  88. """
  89. }
  90. }
  91. }
  92. --------------------------------------------------
  93. // NOTCONSOLE
  94. [discrete]
  95. [[painless-time-features]]
  96. ==== Getting time features as scripted fields
  97. This snippet shows how to extract time based features by using Painless in a
  98. {transform}. The snippet uses an index where `@timestamp` is defined as a `date`
  99. type field.
  100. [source,js]
  101. --------------------------------------------------
  102. "aggregations": {
  103. "script_fields": {
  104. "hour_of_day": { <1>
  105. "script": {
  106. "lang": "painless",
  107. "source": """
  108. ZonedDateTime date = doc['@timestamp'].value; <2>
  109. return date.getHour(); <3>
  110. """
  111. }
  112. },
  113. "month_of_year": { <4>
  114. "script": {
  115. "lang": "painless",
  116. "source": """
  117. ZonedDateTime date = doc['@timestamp'].value; <5>
  118. return date.getMonthValue(); <6>
  119. """
  120. }
  121. }
  122. },
  123. ...
  124. }
  125. --------------------------------------------------
  126. // NOTCONSOLE
  127. <1> Contains the Painless script that returns the hour of the day.
  128. <2> Sets `date` based on the timestamp of the document.
  129. <3> Returns the hour value from `date`.
  130. <4> Contains the Painless script that returns the month of the year.
  131. <5> Sets `date` based on the timestamp of the document.
  132. <6> Returns the month value from `date`.
  133. [discrete]
  134. [[painless-group-by]]
  135. ==== Using Painless in `group_by`
  136. It is possible to base the `group_by` property of a {transform} on the output of
  137. a script. The following example uses the {kib} sample web logs dataset. The goal
  138. here is to make the {transform} output easier to understand through normalizing
  139. the value of the fields that the data is grouped by.
  140. [source,console]
  141. --------------------------------------------------
  142. POST _transform/_preview
  143. {
  144. "source": {
  145. "index": [ <1>
  146. "kibana_sample_data_logs"
  147. ]
  148. },
  149. "pivot": {
  150. "group_by": {
  151. "agent": {
  152. "terms": {
  153. "script": { <2>
  154. "source": """String agent = doc['agent.keyword'].value;
  155. if (agent.contains("MSIE")) {
  156. return "internet explorer";
  157. } else if (agent.contains("AppleWebKit")) {
  158. return "safari";
  159. } else if (agent.contains('Firefox')) {
  160. return "firefox";
  161. } else { return agent }""",
  162. "lang": "painless"
  163. }
  164. }
  165. }
  166. },
  167. "aggregations": { <3>
  168. "200": {
  169. "filter": {
  170. "term": {
  171. "response": "200"
  172. }
  173. }
  174. },
  175. "404": {
  176. "filter": {
  177. "term": {
  178. "response": "404"
  179. }
  180. }
  181. },
  182. "503": {
  183. "filter": {
  184. "term": {
  185. "response": "503"
  186. }
  187. }
  188. }
  189. }
  190. },
  191. "dest": { <4>
  192. "index": "pivot_logs"
  193. }
  194. }
  195. --------------------------------------------------
  196. // TEST[skip:setup kibana sample data]
  197. <1> Specifies the source index or indices.
  198. <2> The script defines an `agent` string based on the `agent` field of the
  199. documents, then iterates through the values. If an `agent` field contains
  200. "MSIE", than the script returns "Internet Explorer". If it contains
  201. `AppleWebKit`, it returns "safari". It returns "firefox" if the field value
  202. contains "Firefox". Finally, in every other case, the value of the field is
  203. returned.
  204. <3> The aggregations object contains filters that narrow down the results to
  205. documents that contains `200`, `404`, or `503` values in the `response` field.
  206. <4> Specifies the destination index of the {transform}.
  207. The API returns the following result:
  208. [source,js]
  209. --------------------------------------------------
  210. {
  211. "preview" : [
  212. {
  213. "agent" : "firefox",
  214. "200" : 4931,
  215. "404" : 259,
  216. "503" : 172
  217. },
  218. {
  219. "agent" : "internet explorer",
  220. "200" : 3674,
  221. "404" : 210,
  222. "503" : 126
  223. },
  224. {
  225. "agent" : "safari",
  226. "200" : 4227,
  227. "404" : 332,
  228. "503" : 143
  229. }
  230. ],
  231. "mappings" : {
  232. "properties" : {
  233. "200" : {
  234. "type" : "long"
  235. },
  236. "agent" : {
  237. "type" : "keyword"
  238. },
  239. "404" : {
  240. "type" : "long"
  241. },
  242. "503" : {
  243. "type" : "long"
  244. }
  245. }
  246. }
  247. }
  248. --------------------------------------------------
  249. // NOTCONSOLE
  250. You can see that the `agent` values are simplified so it is easier to interpret
  251. them. The table below shows how normalization modifies the output of the
  252. {transform} in our example compared to the non-normalized values.
  253. [width="50%"]
  254. |===
  255. | Non-normalized `agent` value | Normalized `agent` value
  256. | "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)" | "internet explorer"
  257. | "Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.50 Safari/534.24" | "safari"
  258. | "Mozilla/5.0 (X11; Linux x86_64; rv:6.0a1) Gecko/20110421 Firefox/6.0a1" | "firefox"
  259. |===
  260. [discrete]
  261. [[painless-bucket-script]]
  262. ==== Getting duration by using bucket script
  263. This example shows you how to get the duration of a session by client IP from a
  264. data log by using
  265. {ref}/search-aggregations-pipeline-bucket-script-aggregation.html[bucket script].
  266. The example uses the {kib} sample web logs dataset.
  267. [source,console]
  268. --------------------------------------------------
  269. PUT _transform/data_log
  270. {
  271. "source": {
  272. "index": "kibana_sample_data_logs"
  273. },
  274. "dest": {
  275. "index": "data-logs-by-client"
  276. },
  277. "pivot": {
  278. "group_by": {
  279. "machine.os": {"terms": {"field": "machine.os.keyword"}},
  280. "machine.ip": {"terms": {"field": "clientip"}}
  281. },
  282. "aggregations": {
  283. "time_frame.lte": {
  284. "max": {
  285. "field": "timestamp"
  286. }
  287. },
  288. "time_frame.gte": {
  289. "min": {
  290. "field": "timestamp"
  291. }
  292. },
  293. "time_length": { <1>
  294. "bucket_script": {
  295. "buckets_path": { <2>
  296. "min": "time_frame.gte.value",
  297. "max": "time_frame.lte.value"
  298. },
  299. "script": "params.max - params.min" <3>
  300. }
  301. }
  302. }
  303. }
  304. }
  305. --------------------------------------------------
  306. // TEST[skip:setup kibana sample data]
  307. <1> To define the length of the sessions, we use a bucket script.
  308. <2> The bucket path is a map of script variables and their associated path to
  309. the buckets you want to use for the variable. In this particular case, `min` and
  310. `max` are variables mapped to `time_frame.gte.value` and `time_frame.lte.value`.
  311. <3> Finally, the script substracts the start date of the session from the end
  312. date which results in the duration of the session.
  313. [discrete]
  314. [[painless-count-http]]
  315. ==== Counting HTTP responses by using scripted metric aggregation
  316. You can count the different HTTP response types in a web log data set by using
  317. scripted metric aggregation as part of the {transform}. The example below
  318. assumes that the HTTP response codes are stored as keywords in the `response`
  319. field of the documents.
  320. [source,js]
  321. --------------------------------------------------
  322. "aggregations": { <1>
  323. "responses.counts": { <2>
  324. "scripted_metric": { <3>
  325. "init_script": "state.responses = ['error':0L,'success':0L,'other':0L]", <4>
  326. "map_script": """ <5>
  327. def code = doc['response.keyword'].value;
  328. if (code.startsWith('5') || code.startsWith('4')) {
  329. state.responses.error += 1 ;
  330. } else if(code.startsWith('2')) {
  331. state.responses.success += 1;
  332. } else {
  333. state.responses.other += 1;
  334. }
  335. """,
  336. "combine_script": "state.responses", <6>
  337. "reduce_script": """ <7>
  338. def counts = ['error': 0L, 'success': 0L, 'other': 0L];
  339. for (responses in states) {
  340. counts.error += responses['error'];
  341. counts.success += responses['success'];
  342. counts.other += responses['other'];
  343. }
  344. return counts;
  345. """
  346. }
  347. },
  348. ...
  349. }
  350. --------------------------------------------------
  351. // NOTCONSOLE
  352. <1> The `aggregations` object of the {transform} that contains all aggregations.
  353. <2> Object of the `scripted_metric` aggregation.
  354. <3> This `scripted_metric` performs a distributed operation on the web log data
  355. to count specific types of HTTP responses (error, success, and other).
  356. <4> The `init_script` creates a `responses` array in the `state` object with
  357. three properties (`error`, `success`, `other`) with long data type.
  358. <5> The `map_script` defines `code` based on the `response.keyword` value of the
  359. document, then it counts the errors, successes, and other responses based on the
  360. first digit of the responses.
  361. <6> The `combine_script` returns `state.responses` from each shard.
  362. <7> The `reduce_script` creates a `counts` array with the `error`, `success`,
  363. and `other` properties, then iterates through the value of `responses` returned
  364. by each shard and assigns the different response types to the appropriate
  365. properties of the `counts` object; error responses to the error counts, success
  366. responses to the success counts, and other responses to the other counts.
  367. Finally, returns the `counts` array with the response counts.
  368. [discrete]
  369. [[painless-compare]]
  370. ==== Comparing indices by using scripted metric aggregations
  371. This example shows how to compare the content of two indices by a {transform}
  372. that uses a scripted metric aggregation.
  373. [source,console]
  374. --------------------------------------------------
  375. POST _transform/_preview
  376. {
  377. "id" : "index_compare",
  378. "source" : { <1>
  379. "index" : [
  380. "index1",
  381. "index2"
  382. ],
  383. "query" : {
  384. "match_all" : { }
  385. }
  386. },
  387. "dest" : { <2>
  388. "index" : "compare"
  389. },
  390. "pivot" : {
  391. "group_by" : {
  392. "unique-id" : {
  393. "terms" : {
  394. "field" : "<unique-id-field>" <3>
  395. }
  396. }
  397. },
  398. "aggregations" : {
  399. "compare" : { <4>
  400. "scripted_metric" : {
  401. "init_script" : "",
  402. "map_script" : "state.doc = new HashMap(params['_source'])", <5>
  403. "combine_script" : "return state", <6>
  404. "reduce_script" : """ <7>
  405. if (states.size() != 2) {
  406. return "count_mismatch"
  407. }
  408. if (states.get(0).equals(states.get(1))) {
  409. return "match"
  410. } else {
  411. return "mismatch"
  412. }
  413. """
  414. }
  415. }
  416. }
  417. }
  418. }
  419. --------------------------------------------------
  420. // TEST[skip:setup kibana sample data]
  421. <1> The indices referenced in the `source` object are compared to each other.
  422. <2> The `dest` index contains the results of the comparison.
  423. <3> The `group_by` field needs to be a unique identifier for each document.
  424. <4> Object of the `scripted_metric` aggregation.
  425. <5> The `map_script` defines `doc` in the state object. By using
  426. `new HashMap(...)` you copy the source document, this is important whenever you
  427. want to pass the full source object from one phase to the next.
  428. <6> The `combine_script` returns `state` from each shard.
  429. <7> The `reduce_script` checks if the size of the indices are equal. If they are
  430. not equal, than it reports back a `count_mismatch`. Then it iterates through all
  431. the values of the two indices and compare them. If the values are equal, then it
  432. returns a `match`, otherwise returns a `mismatch`.
  433. [discrete]
  434. [[painless-web-session]]
  435. ==== Getting web session details by using scripted metric aggregation
  436. This example shows how to derive multiple features from a single transaction.
  437. Let's take a look on the example source document from the data:
  438. .Source document
  439. [%collapsible%open]
  440. =====
  441. [source,js]
  442. --------------------------------------------------
  443. {
  444. "_index":"apache-sessions",
  445. "_type":"_doc",
  446. "_id":"KvzSeGoB4bgw0KGbE3wP",
  447. "_score":1.0,
  448. "_source":{
  449. "@timestamp":1484053499256,
  450. "apache":{
  451. "access":{
  452. "sessionid":"571604f2b2b0c7b346dc685eeb0e2306774a63c2",
  453. "url":"http://www.leroymerlin.fr/v3/search/search.do?keyword=Carrelage%20salle%20de%20bain",
  454. "path":"/v3/search/search.do",
  455. "query":"keyword=Carrelage%20salle%20de%20bain",
  456. "referrer":"http://www.leroymerlin.fr/v3/p/produits/carrelage-parquet-sol-souple/carrelage-sol-et-mur/decor-listel-et-accessoires-carrelage-mural-l1308217717?resultOffset=0&resultLimit=51&resultListShape=MOSAIC&priceStyle=SALEUNIT_PRICE",
  457. "user_agent":{
  458. "original":"Mobile Safari 10.0 Mac OS X (iPad) Apple Inc.",
  459. "os_name":"Mac OS X (iPad)"
  460. },
  461. "remote_ip":"0337b1fa-5ed4-af81-9ef4-0ec53be0f45d",
  462. "geoip":{
  463. "country_iso_code":"FR",
  464. "location":{
  465. "lat":48.86,
  466. "lon":2.35
  467. }
  468. },
  469. "response_code":200,
  470. "method":"GET"
  471. }
  472. }
  473. }
  474. }
  475. ...
  476. --------------------------------------------------
  477. // NOTCONSOLE
  478. =====
  479. By using the `sessionid` as a group-by field, you are able to enumerate events
  480. through the session and get more details of the session by using scripted metric
  481. aggregation.
  482. [source,js]
  483. --------------------------------------------------
  484. POST _transform/_preview
  485. {
  486. "source": {
  487. "index": "apache-sessions"
  488. },
  489. "pivot": {
  490. "group_by": {
  491. "sessionid": { <1>
  492. "terms": {
  493. "field": "apache.access.sessionid"
  494. }
  495. }
  496. },
  497. "aggregations": { <2>
  498. "distinct_paths": {
  499. "cardinality": {
  500. "field": "apache.access.path"
  501. }
  502. },
  503. "num_pages_viewed": {
  504. "value_count": {
  505. "field": "apache.access.url"
  506. }
  507. },
  508. "session_details": {
  509. "scripted_metric": {
  510. "init_script": "state.docs = []", <3>
  511. "map_script": """ <4>
  512. Map span = [
  513. '@timestamp':doc['@timestamp'].value,
  514. 'url':doc['apache.access.url'].value,
  515. 'referrer':doc['apache.access.referrer'].value
  516. ];
  517. state.docs.add(span)
  518. """,
  519. "combine_script": "return state.docs;", <5>
  520. "reduce_script": """ <6>
  521. def all_docs = [];
  522. for (s in states) {
  523. for (span in s) {
  524. all_docs.add(span);
  525. }
  526. }
  527. all_docs.sort((HashMap o1, HashMap o2)->o1['@timestamp'].millis.compareTo(o2['@timestamp'].millis));
  528. def size = all_docs.size();
  529. def min_time = all_docs[0]['@timestamp'];
  530. def max_time = all_docs[size-1]['@timestamp'];
  531. def duration = max_time.millis - min_time.millis;
  532. def entry_page = all_docs[0]['url'];
  533. def exit_path = all_docs[size-1]['url'];
  534. def first_referrer = all_docs[0]['referrer'];
  535. def ret = new HashMap();
  536. ret['first_time'] = min_time;
  537. ret['last_time'] = max_time;
  538. ret['duration'] = duration;
  539. ret['entry_page'] = entry_page;
  540. ret['exit_path'] = exit_path;
  541. ret['first_referrer'] = first_referrer;
  542. return ret;
  543. """
  544. }
  545. }
  546. }
  547. }
  548. }
  549. --------------------------------------------------
  550. // NOTCONSOLE
  551. <1> The data is grouped by `sessionid`.
  552. <2> The aggregations counts the number of paths and enumerate the viewed pages
  553. during the session.
  554. <3> The `init_script` creates an array type `doc` in the `state` object.
  555. <4> The `map_script` defines a `span` array with a timestamp, a URL, and a
  556. referrer value which are based on the corresponding values of the document, then
  557. adds the value of the `span` array to the `doc` object.
  558. <5> The `combine_script` returns `state.docs` from each shard.
  559. <6> The `reduce_script` defines various objects like `min_time`, `max_time`, and
  560. `duration` based on the document fields, then declares a `ret` object, and
  561. copies the source document by using `new HashMap ()`. Next, the script defines
  562. `first_time`, `last_time`, `duration` and other fields inside the `ret` object
  563. based on the corresponding object defined earlier, finally returns `ret`.
  564. The API call results in a similar response:
  565. [source,js]
  566. --------------------------------------------------
  567. {
  568. "num_pages_viewed" : 2.0,
  569. "session_details" : {
  570. "duration" : 131374,
  571. "first_referrer" : "https://www.bing.com/",
  572. "entry_page" : "http://www.leroymerlin.fr/v3/p/produits/materiaux-menuiserie/porte-coulissante-porte-interieure-escalier-et-rambarde/barriere-de-securite-l1308218463",
  573. "first_time" : "2017-01-10T21:22:52.982Z",
  574. "last_time" : "2017-01-10T21:25:04.356Z",
  575. "exit_path" : "http://www.leroymerlin.fr/v3/p/produits/materiaux-menuiserie/porte-coulissante-porte-interieure-escalier-et-rambarde/barriere-de-securite-l1308218463?__result-wrapper?pageTemplate=Famille%2FMat%C3%A9riaux+et+menuiserie&resultOffset=0&resultLimit=50&resultListShape=PLAIN&nomenclatureId=17942&priceStyle=SALEUNIT_PRICE&fcr=1&*4294718806=4294718806&*14072=14072&*4294718593=4294718593&*17942=17942"
  576. },
  577. "distinct_paths" : 1.0,
  578. "sessionid" : "000046f8154a80fd89849369c984b8cc9d795814"
  579. },
  580. {
  581. "num_pages_viewed" : 10.0,
  582. "session_details" : {
  583. "duration" : 343112,
  584. "first_referrer" : "https://www.google.fr/",
  585. "entry_page" : "http://www.leroymerlin.fr/",
  586. "first_time" : "2017-01-10T16:57:39.937Z",
  587. "last_time" : "2017-01-10T17:03:23.049Z",
  588. "exit_path" : "http://www.leroymerlin.fr/v3/p/produits/porte-de-douche-coulissante-adena-e168578"
  589. },
  590. "distinct_paths" : 8.0,
  591. "sessionid" : "000087e825da1d87a332b8f15fa76116c7467da6"
  592. }
  593. ...
  594. --------------------------------------------------
  595. // NOTCONSOLE