painless-examples.asciidoc 21 KB

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