painless-examples.asciidoc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. [role="xpack"]
  2. [testenv="basic"]
  3. [[transform-painless-examples]]
  4. = Painless examples for {transforms}
  5. ++++
  6. <titleabbrev>Painless examples</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. [[painless-group-by]]
  142. == Using Painless in `group_by`
  143. It is possible to base the `group_by` property of a {transform} on the output of
  144. a script. The following example uses the {kib} sample web logs dataset. The goal
  145. here is to make the {transform} output easier to understand through normalizing
  146. the value of the fields that the data is grouped by.
  147. [source,console]
  148. --------------------------------------------------
  149. POST _transform/_preview
  150. {
  151. "source": {
  152. "index": [ <1>
  153. "kibana_sample_data_logs"
  154. ]
  155. },
  156. "pivot": {
  157. "group_by": {
  158. "agent": {
  159. "terms": {
  160. "script": { <2>
  161. "source": """String agent = doc['agent.keyword'].value;
  162. if (agent.contains("MSIE")) {
  163. return "internet explorer";
  164. } else if (agent.contains("AppleWebKit")) {
  165. return "safari";
  166. } else if (agent.contains('Firefox')) {
  167. return "firefox";
  168. } else { return agent }""",
  169. "lang": "painless"
  170. }
  171. }
  172. }
  173. },
  174. "aggregations": { <3>
  175. "200": {
  176. "filter": {
  177. "term": {
  178. "response": "200"
  179. }
  180. }
  181. },
  182. "404": {
  183. "filter": {
  184. "term": {
  185. "response": "404"
  186. }
  187. }
  188. },
  189. "503": {
  190. "filter": {
  191. "term": {
  192. "response": "503"
  193. }
  194. }
  195. }
  196. }
  197. },
  198. "dest": { <4>
  199. "index": "pivot_logs"
  200. }
  201. }
  202. --------------------------------------------------
  203. // TEST[skip:setup kibana sample data]
  204. <1> Specifies the source index or indices.
  205. <2> The script defines an `agent` string based on the `agent` field of the
  206. documents, then iterates through the values. If an `agent` field contains
  207. "MSIE", than the script returns "Internet Explorer". If it contains
  208. `AppleWebKit`, it returns "safari". It returns "firefox" if the field value
  209. contains "Firefox". Finally, in every other case, the value of the field is
  210. returned.
  211. <3> The aggregations object contains filters that narrow down the results to
  212. documents that contains `200`, `404`, or `503` values in the `response` field.
  213. <4> Specifies the destination index of the {transform}.
  214. The API returns the following result:
  215. [source,js]
  216. --------------------------------------------------
  217. {
  218. "preview" : [
  219. {
  220. "agent" : "firefox",
  221. "200" : 4931,
  222. "404" : 259,
  223. "503" : 172
  224. },
  225. {
  226. "agent" : "internet explorer",
  227. "200" : 3674,
  228. "404" : 210,
  229. "503" : 126
  230. },
  231. {
  232. "agent" : "safari",
  233. "200" : 4227,
  234. "404" : 332,
  235. "503" : 143
  236. }
  237. ],
  238. "mappings" : {
  239. "properties" : {
  240. "200" : {
  241. "type" : "long"
  242. },
  243. "agent" : {
  244. "type" : "keyword"
  245. },
  246. "404" : {
  247. "type" : "long"
  248. },
  249. "503" : {
  250. "type" : "long"
  251. }
  252. }
  253. }
  254. }
  255. --------------------------------------------------
  256. // NOTCONSOLE
  257. You can see that the `agent` values are simplified so it is easier to interpret
  258. them. The table below shows how normalization modifies the output of the
  259. {transform} in our example compared to the non-normalized values.
  260. [width="50%"]
  261. |===
  262. | Non-normalized `agent` value | Normalized `agent` value
  263. | "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)" | "internet explorer"
  264. | "Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.50 Safari/534.24" | "safari"
  265. | "Mozilla/5.0 (X11; Linux x86_64; rv:6.0a1) Gecko/20110421 Firefox/6.0a1" | "firefox"
  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'].millis.compareTo(o2['@timestamp'].millis));
  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.millis - min_time.millis;
  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" : 131374,
  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" : 343112,
  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