painless-examples.asciidoc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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. [[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. [[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}. The example below
  315. assumes that the HTTP response codes are stored as keywords in the `response`
  316. field of the documents.
  317. [source,js]
  318. --------------------------------------------------
  319. "aggregations": { <1>
  320. "responses.counts": { <2>
  321. "scripted_metric": { <3>
  322. "init_script": "state.responses = ['error':0L,'success':0L,'other':0L]", <4>
  323. "map_script": """ <5>
  324. def code = doc['response.keyword'].value;
  325. if (code.startsWith('5') || code.startsWith('4')) {
  326. state.responses.error += 1 ;
  327. } else if(code.startsWith('2')) {
  328. state.responses.success += 1;
  329. } else {
  330. state.responses.other += 1;
  331. }
  332. """,
  333. "combine_script": "state.responses", <6>
  334. "reduce_script": """ <7>
  335. def counts = ['error': 0L, 'success': 0L, 'other': 0L];
  336. for (responses in states) {
  337. counts.error += responses['error'];
  338. counts.success += responses['success'];
  339. counts.other += responses['other'];
  340. }
  341. return counts;
  342. """
  343. }
  344. },
  345. ...
  346. }
  347. --------------------------------------------------
  348. // NOTCONSOLE
  349. <1> The `aggregations` object of the {transform} that contains all aggregations.
  350. <2> Object of the `scripted_metric` aggregation.
  351. <3> This `scripted_metric` performs a distributed operation on the web log data
  352. to count specific types of HTTP responses (error, success, and other).
  353. <4> The `init_script` creates a `responses` array in the `state` object with
  354. three properties (`error`, `success`, `other`) with long data type.
  355. <5> The `map_script` defines `code` based on the `response.keyword` value of the
  356. document, then it counts the errors, successes, and other responses based on the
  357. first digit of the responses.
  358. <6> The `combine_script` returns `state.responses` from each shard.
  359. <7> The `reduce_script` creates a `counts` array with the `error`, `success`,
  360. and `other` properties, then iterates through the value of `responses` returned
  361. by each shard and assigns the different response types to the appropriate
  362. properties of the `counts` object; error responses to the error counts, success
  363. responses to the success counts, and other responses to the other counts.
  364. Finally, returns the `counts` array with the response counts.
  365. [[painless-compare]]
  366. == Comparing indices by using scripted metric aggregations
  367. This example shows how to compare the content of two indices by a {transform}
  368. that uses a scripted metric aggregation.
  369. [source,console]
  370. --------------------------------------------------
  371. POST _transform/_preview
  372. {
  373. "id" : "index_compare",
  374. "source" : { <1>
  375. "index" : [
  376. "index1",
  377. "index2"
  378. ],
  379. "query" : {
  380. "match_all" : { }
  381. }
  382. },
  383. "dest" : { <2>
  384. "index" : "compare"
  385. },
  386. "pivot" : {
  387. "group_by" : {
  388. "unique-id" : {
  389. "terms" : {
  390. "field" : "<unique-id-field>" <3>
  391. }
  392. }
  393. },
  394. "aggregations" : {
  395. "compare" : { <4>
  396. "scripted_metric" : {
  397. "init_script" : "",
  398. "map_script" : "state.doc = new HashMap(params['_source'])", <5>
  399. "combine_script" : "return state", <6>
  400. "reduce_script" : """ <7>
  401. if (states.size() != 2) {
  402. return "count_mismatch"
  403. }
  404. if (states.get(0).equals(states.get(1))) {
  405. return "match"
  406. } else {
  407. return "mismatch"
  408. }
  409. """
  410. }
  411. }
  412. }
  413. }
  414. }
  415. --------------------------------------------------
  416. // TEST[skip:setup kibana sample data]
  417. <1> The indices referenced in the `source` object are compared to each other.
  418. <2> The `dest` index contains the results of the comparison.
  419. <3> The `group_by` field needs to be a unique identifier for each document.
  420. <4> Object of the `scripted_metric` aggregation.
  421. <5> The `map_script` defines `doc` in the state object. By using
  422. `new HashMap(...)` you copy the source document, this is important whenever you
  423. want to pass the full source object from one phase to the next.
  424. <6> The `combine_script` returns `state` from each shard.
  425. <7> The `reduce_script` checks if the size of the indices are equal. If they are
  426. not equal, than it reports back a `count_mismatch`. Then it iterates through all
  427. the values of the two indices and compare them. If the values are equal, then it
  428. returns a `match`, otherwise returns a `mismatch`.
  429. [[painless-web-session]]
  430. == Getting web session details by using scripted metric aggregation
  431. This example shows how to derive multiple features from a single transaction.
  432. Let's take a look on the example source document from the data:
  433. .Source document
  434. [%collapsible%open]
  435. =====
  436. [source,js]
  437. --------------------------------------------------
  438. {
  439. "_index":"apache-sessions",
  440. "_type":"_doc",
  441. "_id":"KvzSeGoB4bgw0KGbE3wP",
  442. "_score":1.0,
  443. "_source":{
  444. "@timestamp":1484053499256,
  445. "apache":{
  446. "access":{
  447. "sessionid":"571604f2b2b0c7b346dc685eeb0e2306774a63c2",
  448. "url":"http://www.leroymerlin.fr/v3/search/search.do?keyword=Carrelage%20salle%20de%20bain",
  449. "path":"/v3/search/search.do",
  450. "query":"keyword=Carrelage%20salle%20de%20bain",
  451. "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",
  452. "user_agent":{
  453. "original":"Mobile Safari 10.0 Mac OS X (iPad) Apple Inc.",
  454. "os_name":"Mac OS X (iPad)"
  455. },
  456. "remote_ip":"0337b1fa-5ed4-af81-9ef4-0ec53be0f45d",
  457. "geoip":{
  458. "country_iso_code":"FR",
  459. "location":{
  460. "lat":48.86,
  461. "lon":2.35
  462. }
  463. },
  464. "response_code":200,
  465. "method":"GET"
  466. }
  467. }
  468. }
  469. }
  470. ...
  471. --------------------------------------------------
  472. // NOTCONSOLE
  473. =====
  474. By using the `sessionid` as a group-by field, you are able to enumerate events
  475. through the session and get more details of the session by using scripted metric
  476. aggregation.
  477. [source,js]
  478. --------------------------------------------------
  479. POST _transform/_preview
  480. {
  481. "source": {
  482. "index": "apache-sessions"
  483. },
  484. "pivot": {
  485. "group_by": {
  486. "sessionid": { <1>
  487. "terms": {
  488. "field": "apache.access.sessionid"
  489. }
  490. }
  491. },
  492. "aggregations": { <2>
  493. "distinct_paths": {
  494. "cardinality": {
  495. "field": "apache.access.path"
  496. }
  497. },
  498. "num_pages_viewed": {
  499. "value_count": {
  500. "field": "apache.access.url"
  501. }
  502. },
  503. "session_details": {
  504. "scripted_metric": {
  505. "init_script": "state.docs = []", <3>
  506. "map_script": """ <4>
  507. Map span = [
  508. '@timestamp':doc['@timestamp'].value,
  509. 'url':doc['apache.access.url'].value,
  510. 'referrer':doc['apache.access.referrer'].value
  511. ];
  512. state.docs.add(span)
  513. """,
  514. "combine_script": "return state.docs;", <5>
  515. "reduce_script": """ <6>
  516. def all_docs = [];
  517. for (s in states) {
  518. for (span in s) {
  519. all_docs.add(span);
  520. }
  521. }
  522. all_docs.sort((HashMap o1, HashMap o2)->o1['@timestamp'].millis.compareTo(o2['@timestamp'].millis));
  523. def size = all_docs.size();
  524. def min_time = all_docs[0]['@timestamp'];
  525. def max_time = all_docs[size-1]['@timestamp'];
  526. def duration = max_time.millis - min_time.millis;
  527. def entry_page = all_docs[0]['url'];
  528. def exit_path = all_docs[size-1]['url'];
  529. def first_referrer = all_docs[0]['referrer'];
  530. def ret = new HashMap();
  531. ret['first_time'] = min_time;
  532. ret['last_time'] = max_time;
  533. ret['duration'] = duration;
  534. ret['entry_page'] = entry_page;
  535. ret['exit_path'] = exit_path;
  536. ret['first_referrer'] = first_referrer;
  537. return ret;
  538. """
  539. }
  540. }
  541. }
  542. }
  543. }
  544. --------------------------------------------------
  545. // NOTCONSOLE
  546. <1> The data is grouped by `sessionid`.
  547. <2> The aggregations counts the number of paths and enumerate the viewed pages
  548. during the session.
  549. <3> The `init_script` creates an array type `doc` in the `state` object.
  550. <4> The `map_script` defines a `span` array with a timestamp, a URL, and a
  551. referrer value which are based on the corresponding values of the document, then
  552. adds the value of the `span` array to the `doc` object.
  553. <5> The `combine_script` returns `state.docs` from each shard.
  554. <6> The `reduce_script` defines various objects like `min_time`, `max_time`, and
  555. `duration` based on the document fields, then declares a `ret` object, and
  556. copies the source document by using `new HashMap ()`. Next, the script defines
  557. `first_time`, `last_time`, `duration` and other fields inside the `ret` object
  558. based on the corresponding object defined earlier, finally returns `ret`.
  559. The API call results in a similar response:
  560. [source,js]
  561. --------------------------------------------------
  562. {
  563. "num_pages_viewed" : 2.0,
  564. "session_details" : {
  565. "duration" : 131374,
  566. "first_referrer" : "https://www.bing.com/",
  567. "entry_page" : "http://www.leroymerlin.fr/v3/p/produits/materiaux-menuiserie/porte-coulissante-porte-interieure-escalier-et-rambarde/barriere-de-securite-l1308218463",
  568. "first_time" : "2017-01-10T21:22:52.982Z",
  569. "last_time" : "2017-01-10T21:25:04.356Z",
  570. "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"
  571. },
  572. "distinct_paths" : 1.0,
  573. "sessionid" : "000046f8154a80fd89849369c984b8cc9d795814"
  574. },
  575. {
  576. "num_pages_viewed" : 10.0,
  577. "session_details" : {
  578. "duration" : 343112,
  579. "first_referrer" : "https://www.google.fr/",
  580. "entry_page" : "http://www.leroymerlin.fr/",
  581. "first_time" : "2017-01-10T16:57:39.937Z",
  582. "last_time" : "2017-01-10T17:03:23.049Z",
  583. "exit_path" : "http://www.leroymerlin.fr/v3/p/produits/porte-de-douche-coulissante-adena-e168578"
  584. },
  585. "distinct_paths" : 8.0,
  586. "sessionid" : "000087e825da1d87a332b8f15fa76116c7467da6"
  587. }
  588. ...
  589. --------------------------------------------------
  590. // NOTCONSOLE