painless-examples.asciidoc 21 KB

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