painless-examples.asciidoc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. [role="xpack"]
  2. [testenv="basic"]
  3. [[transform-painless-examples]]
  4. = Painless examples for {transforms}
  5. ++++
  6. <titleabbrev>Painless examples</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. [[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 latest 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['@timestamp'].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. [[painless-time-features]]
  94. == Getting time features by using aggregations
  95. This snippet shows how to extract time based features by using Painless in a
  96. {transform}. The snippet uses an index where `@timestamp` is defined as a `date`
  97. type field.
  98. [source,js]
  99. --------------------------------------------------
  100. "aggregations": {
  101. "avg_hour_of_day": { <1>
  102. "avg":{
  103. "script": { <2>
  104. "source": """
  105. ZonedDateTime date = doc['@timestamp'].value; <3>
  106. return date.getHour(); <4>
  107. """
  108. }
  109. }
  110. },
  111. "avg_month_of_year": { <5>
  112. "avg":{
  113. "script": { <6>
  114. "source": """
  115. ZonedDateTime date = doc['@timestamp'].value; <7>
  116. return date.getMonthValue(); <8>
  117. """
  118. }
  119. }
  120. },
  121. ...
  122. }
  123. --------------------------------------------------
  124. // NOTCONSOLE
  125. <1> Name of the aggregation.
  126. <2> Contains the Painless script that returns the hour of the day.
  127. <3> Sets `date` based on the timestamp of the document.
  128. <4> Returns the hour value from `date`.
  129. <5> Name of the aggregation.
  130. <6> Contains the Painless script that returns the month of the year.
  131. <7> Sets `date` based on the timestamp of the document.
  132. <8> Returns the month value from `date`.
  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. [[painless-bucket-script]]
  260. == Getting duration by using bucket script
  261. This example shows you how to get the duration of a session by client IP from a
  262. data log by using
  263. <<search-aggregations-pipeline-bucket-script-aggregation,bucket script>>.
  264. The example uses the {kib} sample web logs dataset.
  265. [source,console]
  266. --------------------------------------------------
  267. PUT _transform/data_log
  268. {
  269. "source": {
  270. "index": "kibana_sample_data_logs"
  271. },
  272. "dest": {
  273. "index": "data-logs-by-client"
  274. },
  275. "pivot": {
  276. "group_by": {
  277. "machine.os": {"terms": {"field": "machine.os.keyword"}},
  278. "machine.ip": {"terms": {"field": "clientip"}}
  279. },
  280. "aggregations": {
  281. "time_frame.lte": {
  282. "max": {
  283. "field": "timestamp"
  284. }
  285. },
  286. "time_frame.gte": {
  287. "min": {
  288. "field": "timestamp"
  289. }
  290. },
  291. "time_length": { <1>
  292. "bucket_script": {
  293. "buckets_path": { <2>
  294. "min": "time_frame.gte.value",
  295. "max": "time_frame.lte.value"
  296. },
  297. "script": "params.max - params.min" <3>
  298. }
  299. }
  300. }
  301. }
  302. }
  303. --------------------------------------------------
  304. // TEST[skip:setup kibana sample data]
  305. <1> To define the length of the sessions, we use a bucket script.
  306. <2> The bucket path is a map of script variables and their associated path to
  307. the buckets you want to use for the variable. In this particular case, `min` and
  308. `max` are variables mapped to `time_frame.gte.value` and `time_frame.lte.value`.
  309. <3> Finally, the script substracts the start date of the session from the end
  310. date which results in the duration of the session.
  311. [[painless-count-http]]
  312. == Counting HTTP responses by using scripted metric aggregation
  313. You can count the different HTTP response types in a web log data set by using
  314. scripted metric aggregation as part of the {transform}. You can achieve a
  315. similar function with filter aggregations, check the
  316. {ref}/transform-examples.html#example-clientips[Finding suspicious client IPs]
  317. example for details.
  318. The example below assumes that the HTTP response codes are stored as keywords in
  319. the `response` 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. [[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. "map_script" : "state.doc = new HashMap(params['_source'])", <5>
  401. "combine_script" : "return state", <6>
  402. "reduce_script" : """ <7>
  403. if (states.size() != 2) {
  404. return "count_mismatch"
  405. }
  406. if (states.get(0).equals(states.get(1))) {
  407. return "match"
  408. } else {
  409. return "mismatch"
  410. }
  411. """
  412. }
  413. }
  414. }
  415. }
  416. }
  417. --------------------------------------------------
  418. // TEST[skip:setup kibana sample data]
  419. <1> The indices referenced in the `source` object are compared to each other.
  420. <2> The `dest` index contains the results of the comparison.
  421. <3> The `group_by` field needs to be a unique identifier for each document.
  422. <4> Object of the `scripted_metric` aggregation.
  423. <5> The `map_script` defines `doc` in the state object. By using
  424. `new HashMap(...)` you copy the source document, this is important whenever you
  425. want to pass the full source object from one phase to the next.
  426. <6> The `combine_script` returns `state` from each shard.
  427. <7> The `reduce_script` checks if the size of the indices are equal. If they are
  428. not equal, than it reports back a `count_mismatch`. Then it iterates through all
  429. the values of the two indices and compare them. If the values are equal, then it
  430. returns a `match`, otherwise returns a `mismatch`.
  431. [[painless-web-session]]
  432. == Getting web session details by using scripted metric aggregation
  433. This example shows how to derive multiple features from a single transaction.
  434. Let's take a look on the example source document from the data:
  435. .Source document
  436. [%collapsible%open]
  437. =====
  438. [source,js]
  439. --------------------------------------------------
  440. {
  441. "_index":"apache-sessions",
  442. "_type":"_doc",
  443. "_id":"KvzSeGoB4bgw0KGbE3wP",
  444. "_score":1.0,
  445. "_source":{
  446. "@timestamp":1484053499256,
  447. "apache":{
  448. "access":{
  449. "sessionid":"571604f2b2b0c7b346dc685eeb0e2306774a63c2",
  450. "url":"http://www.leroymerlin.fr/v3/search/search.do?keyword=Carrelage%20salle%20de%20bain",
  451. "path":"/v3/search/search.do",
  452. "query":"keyword=Carrelage%20salle%20de%20bain",
  453. "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",
  454. "user_agent":{
  455. "original":"Mobile Safari 10.0 Mac OS X (iPad) Apple Inc.",
  456. "os_name":"Mac OS X (iPad)"
  457. },
  458. "remote_ip":"0337b1fa-5ed4-af81-9ef4-0ec53be0f45d",
  459. "geoip":{
  460. "country_iso_code":"FR",
  461. "location":{
  462. "lat":48.86,
  463. "lon":2.35
  464. }
  465. },
  466. "response_code":200,
  467. "method":"GET"
  468. }
  469. }
  470. }
  471. }
  472. ...
  473. --------------------------------------------------
  474. // NOTCONSOLE
  475. =====
  476. By using the `sessionid` as a group-by field, you are able to enumerate events
  477. through the session and get more details of the session by using scripted metric
  478. aggregation.
  479. [source,js]
  480. --------------------------------------------------
  481. POST _transform/_preview
  482. {
  483. "source": {
  484. "index": "apache-sessions"
  485. },
  486. "pivot": {
  487. "group_by": {
  488. "sessionid": { <1>
  489. "terms": {
  490. "field": "apache.access.sessionid"
  491. }
  492. }
  493. },
  494. "aggregations": { <2>
  495. "distinct_paths": {
  496. "cardinality": {
  497. "field": "apache.access.path"
  498. }
  499. },
  500. "num_pages_viewed": {
  501. "value_count": {
  502. "field": "apache.access.url"
  503. }
  504. },
  505. "session_details": {
  506. "scripted_metric": {
  507. "init_script": "state.docs = []", <3>
  508. "map_script": """ <4>
  509. Map span = [
  510. '@timestamp':doc['@timestamp'].value,
  511. 'url':doc['apache.access.url'].value,
  512. 'referrer':doc['apache.access.referrer'].value
  513. ];
  514. state.docs.add(span)
  515. """,
  516. "combine_script": "return state.docs;", <5>
  517. "reduce_script": """ <6>
  518. def all_docs = [];
  519. for (s in states) {
  520. for (span in s) {
  521. all_docs.add(span);
  522. }
  523. }
  524. all_docs.sort((HashMap o1, HashMap o2)->o1['@timestamp'].millis.compareTo(o2['@timestamp'].millis));
  525. def size = all_docs.size();
  526. def min_time = all_docs[0]['@timestamp'];
  527. def max_time = all_docs[size-1]['@timestamp'];
  528. def duration = max_time.millis - min_time.millis;
  529. def entry_page = all_docs[0]['url'];
  530. def exit_path = all_docs[size-1]['url'];
  531. def first_referrer = all_docs[0]['referrer'];
  532. def ret = new HashMap();
  533. ret['first_time'] = min_time;
  534. ret['last_time'] = max_time;
  535. ret['duration'] = duration;
  536. ret['entry_page'] = entry_page;
  537. ret['exit_path'] = exit_path;
  538. ret['first_referrer'] = first_referrer;
  539. return ret;
  540. """
  541. }
  542. }
  543. }
  544. }
  545. }
  546. --------------------------------------------------
  547. // NOTCONSOLE
  548. <1> The data is grouped by `sessionid`.
  549. <2> The aggregations counts the number of paths and enumerate the viewed pages
  550. during the session.
  551. <3> The `init_script` creates an array type `doc` in the `state` object.
  552. <4> The `map_script` defines a `span` array with a timestamp, a URL, and a
  553. referrer value which are based on the corresponding values of the document, then
  554. adds the value of the `span` array to the `doc` object.
  555. <5> The `combine_script` returns `state.docs` from each shard.
  556. <6> The `reduce_script` defines various objects like `min_time`, `max_time`, and
  557. `duration` based on the document fields, then declares a `ret` object, and
  558. copies the source document by using `new HashMap ()`. Next, the script defines
  559. `first_time`, `last_time`, `duration` and other fields inside the `ret` object
  560. based on the corresponding object defined earlier, finally returns `ret`.
  561. The API call results in a similar response:
  562. [source,js]
  563. --------------------------------------------------
  564. {
  565. "num_pages_viewed" : 2.0,
  566. "session_details" : {
  567. "duration" : 131374,
  568. "first_referrer" : "https://www.bing.com/",
  569. "entry_page" : "http://www.leroymerlin.fr/v3/p/produits/materiaux-menuiserie/porte-coulissante-porte-interieure-escalier-et-rambarde/barriere-de-securite-l1308218463",
  570. "first_time" : "2017-01-10T21:22:52.982Z",
  571. "last_time" : "2017-01-10T21:25:04.356Z",
  572. "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"
  573. },
  574. "distinct_paths" : 1.0,
  575. "sessionid" : "000046f8154a80fd89849369c984b8cc9d795814"
  576. },
  577. {
  578. "num_pages_viewed" : 10.0,
  579. "session_details" : {
  580. "duration" : 343112,
  581. "first_referrer" : "https://www.google.fr/",
  582. "entry_page" : "http://www.leroymerlin.fr/",
  583. "first_time" : "2017-01-10T16:57:39.937Z",
  584. "last_time" : "2017-01-10T17:03:23.049Z",
  585. "exit_path" : "http://www.leroymerlin.fr/v3/p/produits/porte-de-douche-coulissante-adena-e168578"
  586. },
  587. "distinct_paths" : 8.0,
  588. "sessionid" : "000087e825da1d87a332b8f15fa76116c7467da6"
  589. }
  590. ...
  591. --------------------------------------------------
  592. // NOTCONSOLE