painless-examples.asciidoc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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 <<scripted-metric-aggregation-scope,scope of scripts>> for detailed
  73. explanation on the respective scripts.
  74. You can retrieve the last value in a similar way:
  75. [source,js]
  76. --------------------------------------------------
  77. "aggregations": {
  78. "latest_value": {
  79. "scripted_metric": {
  80. "init_script": "state.timestamp_latest = 0L; state.last_value = ''",
  81. "map_script": """
  82. def current_date = doc['@timestamp'].getValue().toInstant().toEpochMilli();
  83. if (current_date > state.timestamp_latest)
  84. {state.timestamp_latest = current_date;
  85. state.last_value = params['_source']['value'];}
  86. """,
  87. "combine_script": "return state",
  88. "reduce_script": """
  89. def last_value = '';
  90. def timestamp_latest = 0L;
  91. for (s in states) {if (s.timestamp_latest > (timestamp_latest))
  92. {timestamp_latest = s.timestamp_latest; last_value = s.last_value;}}
  93. return last_value
  94. """
  95. }
  96. }
  97. }
  98. --------------------------------------------------
  99. // NOTCONSOLE
  100. [[painless-time-features]]
  101. == Getting time features by using aggregations
  102. This snippet shows how to extract time based features by using Painless in a
  103. {transform}. The snippet uses an index where `@timestamp` is defined as a `date`
  104. type field.
  105. [source,js]
  106. --------------------------------------------------
  107. "aggregations": {
  108. "avg_hour_of_day": { <1>
  109. "avg":{
  110. "script": { <2>
  111. "source": """
  112. ZonedDateTime date = doc['@timestamp'].value; <3>
  113. return date.getHour(); <4>
  114. """
  115. }
  116. }
  117. },
  118. "avg_month_of_year": { <5>
  119. "avg":{
  120. "script": { <6>
  121. "source": """
  122. ZonedDateTime date = doc['@timestamp'].value; <7>
  123. return date.getMonthValue(); <8>
  124. """
  125. }
  126. }
  127. },
  128. ...
  129. }
  130. --------------------------------------------------
  131. // NOTCONSOLE
  132. <1> Name of the aggregation.
  133. <2> Contains the Painless script that returns the hour of the day.
  134. <3> Sets `date` based on the timestamp of the document.
  135. <4> Returns the hour value from `date`.
  136. <5> Name of the aggregation.
  137. <6> Contains the Painless script that returns the month of the year.
  138. <7> Sets `date` based on the timestamp of the document.
  139. <8> Returns the month value from `date`.
  140. ////
  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. ////
  268. [[painless-bucket-script]]
  269. == Getting duration by using bucket script
  270. This example shows you how to get the duration of a session by client IP from a
  271. data log by using
  272. <<search-aggregations-pipeline-bucket-script-aggregation,bucket script>>.
  273. The example uses the {kib} sample web logs dataset.
  274. [source,console]
  275. --------------------------------------------------
  276. PUT _transform/data_log
  277. {
  278. "source": {
  279. "index": "kibana_sample_data_logs"
  280. },
  281. "dest": {
  282. "index": "data-logs-by-client"
  283. },
  284. "pivot": {
  285. "group_by": {
  286. "machine.os": {"terms": {"field": "machine.os.keyword"}},
  287. "machine.ip": {"terms": {"field": "clientip"}}
  288. },
  289. "aggregations": {
  290. "time_frame.lte": {
  291. "max": {
  292. "field": "timestamp"
  293. }
  294. },
  295. "time_frame.gte": {
  296. "min": {
  297. "field": "timestamp"
  298. }
  299. },
  300. "time_length": { <1>
  301. "bucket_script": {
  302. "buckets_path": { <2>
  303. "min": "time_frame.gte.value",
  304. "max": "time_frame.lte.value"
  305. },
  306. "script": "params.max - params.min" <3>
  307. }
  308. }
  309. }
  310. }
  311. }
  312. --------------------------------------------------
  313. // TEST[skip:setup kibana sample data]
  314. <1> To define the length of the sessions, we use a bucket script.
  315. <2> The bucket path is a map of script variables and their associated path to
  316. the buckets you want to use for the variable. In this particular case, `min` and
  317. `max` are variables mapped to `time_frame.gte.value` and `time_frame.lte.value`.
  318. <3> Finally, the script substracts the start date of the session from the end
  319. date which results in the duration of the session.
  320. [[painless-count-http]]
  321. == Counting HTTP responses by using scripted metric aggregation
  322. You can count the different HTTP response types in a web log data set by using
  323. scripted metric aggregation as part of the {transform}. You can achieve a
  324. similar function with filter aggregations, check the
  325. {ref}/transform-examples.html#example-clientips[Finding suspicious client IPs]
  326. example for details.
  327. The example below assumes that the HTTP response codes are stored as keywords in
  328. the `response` field of the documents.
  329. [source,js]
  330. --------------------------------------------------
  331. "aggregations": { <1>
  332. "responses.counts": { <2>
  333. "scripted_metric": { <3>
  334. "init_script": "state.responses = ['error':0L,'success':0L,'other':0L]", <4>
  335. "map_script": """ <5>
  336. def code = doc['response.keyword'].value;
  337. if (code.startsWith('5') || code.startsWith('4')) {
  338. state.responses.error += 1 ;
  339. } else if(code.startsWith('2')) {
  340. state.responses.success += 1;
  341. } else {
  342. state.responses.other += 1;
  343. }
  344. """,
  345. "combine_script": "state.responses", <6>
  346. "reduce_script": """ <7>
  347. def counts = ['error': 0L, 'success': 0L, 'other': 0L];
  348. for (responses in states) {
  349. counts.error += responses['error'];
  350. counts.success += responses['success'];
  351. counts.other += responses['other'];
  352. }
  353. return counts;
  354. """
  355. }
  356. },
  357. ...
  358. }
  359. --------------------------------------------------
  360. // NOTCONSOLE
  361. <1> The `aggregations` object of the {transform} that contains all aggregations.
  362. <2> Object of the `scripted_metric` aggregation.
  363. <3> This `scripted_metric` performs a distributed operation on the web log data
  364. to count specific types of HTTP responses (error, success, and other).
  365. <4> The `init_script` creates a `responses` array in the `state` object with
  366. three properties (`error`, `success`, `other`) with long data type.
  367. <5> The `map_script` defines `code` based on the `response.keyword` value of the
  368. document, then it counts the errors, successes, and other responses based on the
  369. first digit of the responses.
  370. <6> The `combine_script` returns `state.responses` from each shard.
  371. <7> The `reduce_script` creates a `counts` array with the `error`, `success`,
  372. and `other` properties, then iterates through the value of `responses` returned
  373. by each shard and assigns the different response types to the appropriate
  374. properties of the `counts` object; error responses to the error counts, success
  375. responses to the success counts, and other responses to the other counts.
  376. Finally, returns the `counts` array with the response counts.
  377. [[painless-compare]]
  378. == Comparing indices by using scripted metric aggregations
  379. This example shows how to compare the content of two indices by a {transform}
  380. that uses a scripted metric aggregation.
  381. [source,console]
  382. --------------------------------------------------
  383. POST _transform/_preview
  384. {
  385. "id" : "index_compare",
  386. "source" : { <1>
  387. "index" : [
  388. "index1",
  389. "index2"
  390. ],
  391. "query" : {
  392. "match_all" : { }
  393. }
  394. },
  395. "dest" : { <2>
  396. "index" : "compare"
  397. },
  398. "pivot" : {
  399. "group_by" : {
  400. "unique-id" : {
  401. "terms" : {
  402. "field" : "<unique-id-field>" <3>
  403. }
  404. }
  405. },
  406. "aggregations" : {
  407. "compare" : { <4>
  408. "scripted_metric" : {
  409. "map_script" : "state.doc = new HashMap(params['_source'])", <5>
  410. "combine_script" : "return state", <6>
  411. "reduce_script" : """ <7>
  412. if (states.size() != 2) {
  413. return "count_mismatch"
  414. }
  415. if (states.get(0).equals(states.get(1))) {
  416. return "match"
  417. } else {
  418. return "mismatch"
  419. }
  420. """
  421. }
  422. }
  423. }
  424. }
  425. }
  426. --------------------------------------------------
  427. // TEST[skip:setup kibana sample data]
  428. <1> The indices referenced in the `source` object are compared to each other.
  429. <2> The `dest` index contains the results of the comparison.
  430. <3> The `group_by` field needs to be a unique identifier for each document.
  431. <4> Object of the `scripted_metric` aggregation.
  432. <5> The `map_script` defines `doc` in the state object. By using
  433. `new HashMap(...)` you copy the source document, this is important whenever you
  434. want to pass the full source object from one phase to the next.
  435. <6> The `combine_script` returns `state` from each shard.
  436. <7> The `reduce_script` checks if the size of the indices are equal. If they are
  437. not equal, than it reports back a `count_mismatch`. Then it iterates through all
  438. the values of the two indices and compare them. If the values are equal, then it
  439. returns a `match`, otherwise returns a `mismatch`.
  440. [[painless-web-session]]
  441. == Getting web session details by using scripted metric aggregation
  442. This example shows how to derive multiple features from a single transaction.
  443. Let's take a look on the example source document from the data:
  444. .Source document
  445. [%collapsible%open]
  446. =====
  447. [source,js]
  448. --------------------------------------------------
  449. {
  450. "_index":"apache-sessions",
  451. "_type":"_doc",
  452. "_id":"KvzSeGoB4bgw0KGbE3wP",
  453. "_score":1.0,
  454. "_source":{
  455. "@timestamp":1484053499256,
  456. "apache":{
  457. "access":{
  458. "sessionid":"571604f2b2b0c7b346dc685eeb0e2306774a63c2",
  459. "url":"http://www.leroymerlin.fr/v3/search/search.do?keyword=Carrelage%20salle%20de%20bain",
  460. "path":"/v3/search/search.do",
  461. "query":"keyword=Carrelage%20salle%20de%20bain",
  462. "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",
  463. "user_agent":{
  464. "original":"Mobile Safari 10.0 Mac OS X (iPad) Apple Inc.",
  465. "os_name":"Mac OS X (iPad)"
  466. },
  467. "remote_ip":"0337b1fa-5ed4-af81-9ef4-0ec53be0f45d",
  468. "geoip":{
  469. "country_iso_code":"FR",
  470. "location":{
  471. "lat":48.86,
  472. "lon":2.35
  473. }
  474. },
  475. "response_code":200,
  476. "method":"GET"
  477. }
  478. }
  479. }
  480. }
  481. ...
  482. --------------------------------------------------
  483. // NOTCONSOLE
  484. =====
  485. By using the `sessionid` as a group-by field, you are able to enumerate events
  486. through the session and get more details of the session by using scripted metric
  487. aggregation.
  488. [source,js]
  489. --------------------------------------------------
  490. POST _transform/_preview
  491. {
  492. "source": {
  493. "index": "apache-sessions"
  494. },
  495. "pivot": {
  496. "group_by": {
  497. "sessionid": { <1>
  498. "terms": {
  499. "field": "apache.access.sessionid"
  500. }
  501. }
  502. },
  503. "aggregations": { <2>
  504. "distinct_paths": {
  505. "cardinality": {
  506. "field": "apache.access.path"
  507. }
  508. },
  509. "num_pages_viewed": {
  510. "value_count": {
  511. "field": "apache.access.url"
  512. }
  513. },
  514. "session_details": {
  515. "scripted_metric": {
  516. "init_script": "state.docs = []", <3>
  517. "map_script": """ <4>
  518. Map span = [
  519. '@timestamp':doc['@timestamp'].value,
  520. 'url':doc['apache.access.url'].value,
  521. 'referrer':doc['apache.access.referrer'].value
  522. ];
  523. state.docs.add(span)
  524. """,
  525. "combine_script": "return state.docs;", <5>
  526. "reduce_script": """ <6>
  527. def all_docs = [];
  528. for (s in states) {
  529. for (span in s) {
  530. all_docs.add(span);
  531. }
  532. }
  533. all_docs.sort((HashMap o1, HashMap o2)->o1['@timestamp'].millis.compareTo(o2['@timestamp'].millis));
  534. def size = all_docs.size();
  535. def min_time = all_docs[0]['@timestamp'];
  536. def max_time = all_docs[size-1]['@timestamp'];
  537. def duration = max_time.millis - min_time.millis;
  538. def entry_page = all_docs[0]['url'];
  539. def exit_path = all_docs[size-1]['url'];
  540. def first_referrer = all_docs[0]['referrer'];
  541. def ret = new HashMap();
  542. ret['first_time'] = min_time;
  543. ret['last_time'] = max_time;
  544. ret['duration'] = duration;
  545. ret['entry_page'] = entry_page;
  546. ret['exit_path'] = exit_path;
  547. ret['first_referrer'] = first_referrer;
  548. return ret;
  549. """
  550. }
  551. }
  552. }
  553. }
  554. }
  555. --------------------------------------------------
  556. // NOTCONSOLE
  557. <1> The data is grouped by `sessionid`.
  558. <2> The aggregations counts the number of paths and enumerate the viewed pages
  559. during the session.
  560. <3> The `init_script` creates an array type `doc` in the `state` object.
  561. <4> The `map_script` defines a `span` array with a timestamp, a URL, and a
  562. referrer value which are based on the corresponding values of the document, then
  563. adds the value of the `span` array to the `doc` object.
  564. <5> The `combine_script` returns `state.docs` from each shard.
  565. <6> The `reduce_script` defines various objects like `min_time`, `max_time`, and
  566. `duration` based on the document fields, then declares a `ret` object, and
  567. copies the source document by using `new HashMap ()`. Next, the script defines
  568. `first_time`, `last_time`, `duration` and other fields inside the `ret` object
  569. based on the corresponding object defined earlier, finally returns `ret`.
  570. The API call results in a similar response:
  571. [source,js]
  572. --------------------------------------------------
  573. {
  574. "num_pages_viewed" : 2.0,
  575. "session_details" : {
  576. "duration" : 131374,
  577. "first_referrer" : "https://www.bing.com/",
  578. "entry_page" : "http://www.leroymerlin.fr/v3/p/produits/materiaux-menuiserie/porte-coulissante-porte-interieure-escalier-et-rambarde/barriere-de-securite-l1308218463",
  579. "first_time" : "2017-01-10T21:22:52.982Z",
  580. "last_time" : "2017-01-10T21:25:04.356Z",
  581. "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"
  582. },
  583. "distinct_paths" : 1.0,
  584. "sessionid" : "000046f8154a80fd89849369c984b8cc9d795814"
  585. },
  586. {
  587. "num_pages_viewed" : 10.0,
  588. "session_details" : {
  589. "duration" : 343112,
  590. "first_referrer" : "https://www.google.fr/",
  591. "entry_page" : "http://www.leroymerlin.fr/",
  592. "first_time" : "2017-01-10T16:57:39.937Z",
  593. "last_time" : "2017-01-10T17:03:23.049Z",
  594. "exit_path" : "http://www.leroymerlin.fr/v3/p/produits/porte-de-douche-coulissante-adena-e168578"
  595. },
  596. "distinct_paths" : 8.0,
  597. "sessionid" : "000087e825da1d87a332b8f15fa76116c7467da6"
  598. }
  599. ...
  600. --------------------------------------------------
  601. // NOTCONSOLE