examples.asciidoc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. [role="xpack"]
  2. [testenv="basic"]
  3. [[transform-examples]]
  4. === {transform-cap} examples
  5. ++++
  6. <titleabbrev>Examples</titleabbrev>
  7. ++++
  8. beta[]
  9. These examples demonstrate how to use {transforms} to derive useful
  10. insights from your data. All the examples use one of the
  11. {kibana-ref}/add-sample-data.html[{kib} sample datasets]. For a more detailed,
  12. step-by-step example, see
  13. <<ecommerce-transforms>>.
  14. * <<example-best-customers>>
  15. * <<example-airline>>
  16. * <<example-clientips>>
  17. [[example-best-customers]]
  18. ==== Finding your best customers
  19. In this example, we use the eCommerce orders sample dataset to find the customers
  20. who spent the most in our hypothetical webshop. Let's transform the data such
  21. that the destination index contains the number of orders, the total price of
  22. the orders, the amount of unique products and the average price per order,
  23. and the total amount of ordered products for each customer.
  24. [source,console]
  25. ----------------------------------
  26. POST _data_frame/transforms/_preview
  27. {
  28. "source": {
  29. "index": "kibana_sample_data_ecommerce"
  30. },
  31. "dest" : { <1>
  32. "index" : "sample_ecommerce_orders_by_customer"
  33. },
  34. "pivot": {
  35. "group_by": { <2>
  36. "user": { "terms": { "field": "user" }},
  37. "customer_id": { "terms": { "field": "customer_id" }}
  38. },
  39. "aggregations": {
  40. "order_count": { "value_count": { "field": "order_id" }},
  41. "total_order_amt": { "sum": { "field": "taxful_total_price" }},
  42. "avg_amt_per_order": { "avg": { "field": "taxful_total_price" }},
  43. "avg_unique_products_per_order": { "avg": { "field": "total_unique_products" }},
  44. "total_unique_products": { "cardinality": { "field": "products.product_id" }}
  45. }
  46. }
  47. }
  48. ----------------------------------
  49. // TEST[skip:setup kibana sample data]
  50. <1> This is the destination index for the {dataframe}. It is ignored by
  51. `_preview`.
  52. <2> Two `group_by` fields have been selected. This means the {dataframe} will
  53. contain a unique row per `user` and `customer_id` combination. Within this
  54. dataset both these fields are unique. By including both in the {dataframe} it
  55. gives more context to the final results.
  56. NOTE: In the example above, condensed JSON formatting has been used for easier
  57. readability of the pivot object.
  58. The preview {transforms} API enables you to see the layout of the
  59. {dataframe} in advance, populated with some sample values. For example:
  60. [source,js]
  61. ----------------------------------
  62. {
  63. "preview" : [
  64. {
  65. "total_order_amt" : 3946.9765625,
  66. "order_count" : 59.0,
  67. "total_unique_products" : 116.0,
  68. "avg_unique_products_per_order" : 2.0,
  69. "customer_id" : "10",
  70. "user" : "recip",
  71. "avg_amt_per_order" : 66.89790783898304
  72. },
  73. ...
  74. ]
  75. }
  76. ----------------------------------
  77. // NOTCONSOLE
  78. This {dataframe} makes it easier to answer questions such as:
  79. * Which customers spend the most?
  80. * Which customers spend the most per order?
  81. * Which customers order most often?
  82. * Which customers ordered the least number of different products?
  83. It's possible to answer these questions using aggregations alone, however
  84. {dataframes} allow us to persist this data as a customer centric index. This
  85. enables us to analyze data at scale and gives more flexibility to explore and
  86. navigate data from a customer centric perspective. In some cases, it can even
  87. make creating visualizations much simpler.
  88. [[example-airline]]
  89. ==== Finding air carriers with the most delays
  90. In this example, we use the Flights sample dataset to find out which air carrier
  91. had the most delays. First, we filter the source data such that it excludes all
  92. the cancelled flights by using a query filter. Then we transform the data to
  93. contain the distinct number of flights, the sum of delayed minutes, and the sum
  94. of the flight minutes by air carrier. Finally, we use a
  95. {ref}/search-aggregations-pipeline-bucket-script-aggregation.html[`bucket_script`]
  96. to determine what percentage of the flight time was actually delay.
  97. [source,console]
  98. ----------------------------------
  99. POST _data_frame/transforms/_preview
  100. {
  101. "source": {
  102. "index": "kibana_sample_data_flights",
  103. "query": { <1>
  104. "bool": {
  105. "filter": [
  106. { "term": { "Cancelled": false } }
  107. ]
  108. }
  109. }
  110. },
  111. "dest" : { <2>
  112. "index" : "sample_flight_delays_by_carrier"
  113. },
  114. "pivot": {
  115. "group_by": { <3>
  116. "carrier": { "terms": { "field": "Carrier" }}
  117. },
  118. "aggregations": {
  119. "flights_count": { "value_count": { "field": "FlightNum" }},
  120. "delay_mins_total": { "sum": { "field": "FlightDelayMin" }},
  121. "flight_mins_total": { "sum": { "field": "FlightTimeMin" }},
  122. "delay_time_percentage": { <4>
  123. "bucket_script": {
  124. "buckets_path": {
  125. "delay_time": "delay_mins_total.value",
  126. "flight_time": "flight_mins_total.value"
  127. },
  128. "script": "(params.delay_time / params.flight_time) * 100"
  129. }
  130. }
  131. }
  132. }
  133. }
  134. ----------------------------------
  135. // TEST[skip:setup kibana sample data]
  136. <1> Filter the source data to select only flights that were not cancelled.
  137. <2> This is the destination index for the {dataframe}. It is ignored by
  138. `_preview`.
  139. <3> The data is grouped by the `Carrier` field which contains the airline name.
  140. <4> This `bucket_script` performs calculations on the results that are returned
  141. by the aggregation. In this particular example, it calculates what percentage of
  142. travel time was taken up by delays.
  143. The preview shows you that the new index would contain data like this for each
  144. carrier:
  145. [source,js]
  146. ----------------------------------
  147. {
  148. "preview" : [
  149. {
  150. "carrier" : "ES-Air",
  151. "flights_count" : 2802.0,
  152. "flight_mins_total" : 1436927.5130677223,
  153. "delay_time_percentage" : 9.335543983955839,
  154. "delay_mins_total" : 134145.0
  155. },
  156. ...
  157. ]
  158. }
  159. ----------------------------------
  160. // NOTCONSOLE
  161. This {dataframe} makes it easier to answer questions such as:
  162. * Which air carrier has the most delays as a percentage of flight time?
  163. NOTE: This data is fictional and does not reflect actual delays
  164. or flight stats for any of the featured destination or origin airports.
  165. [[example-clientips]]
  166. ==== Finding suspicious client IPs by using scripted metrics
  167. With {transforms}, you can use
  168. {ref}/search-aggregations-metrics-scripted-metric-aggregation.html[scripted
  169. metric aggregations] on your data. These aggregations are flexible and make
  170. it possible to perform very complex processing. Let's use scripted metrics to
  171. identify suspicious client IPs in the web log sample dataset.
  172. We transform the data such that the new index contains the sum of bytes and the
  173. number of distinct URLs, agents, incoming requests by location, and geographic
  174. destinations for each client IP. We also use a scripted field to count the
  175. specific types of HTTP responses that each client IP receives. Ultimately, the
  176. example below transforms web log data into an entity centric index where the
  177. entity is `clientip`.
  178. [source,console]
  179. ----------------------------------
  180. POST _data_frame/transforms/_preview
  181. {
  182. "source": {
  183. "index": "kibana_sample_data_logs",
  184. "query": { <1>
  185. "range" : {
  186. "timestamp" : {
  187. "gte" : "now-30d/d"
  188. }
  189. }
  190. }
  191. },
  192. "dest" : { <2>
  193. "index" : "sample_weblogs_by_clientip"
  194. },
  195. "pivot": {
  196. "group_by": { <3>
  197. "clientip": { "terms": { "field": "clientip" } }
  198. },
  199. "aggregations": {
  200. "url_dc": { "cardinality": { "field": "url.keyword" }},
  201. "bytes_sum": { "sum": { "field": "bytes" }},
  202. "geo.src_dc": { "cardinality": { "field": "geo.src" }},
  203. "agent_dc": { "cardinality": { "field": "agent.keyword" }},
  204. "geo.dest_dc": { "cardinality": { "field": "geo.dest" }},
  205. "responses.total": { "value_count": { "field": "timestamp" }},
  206. "responses.counts": { <4>
  207. "scripted_metric": {
  208. "init_script": "state.responses = ['error':0L,'success':0L,'other':0L]",
  209. "map_script": """
  210. def code = doc['response.keyword'].value;
  211. if (code.startsWith('5') || code.startsWith('4')) {
  212. state.responses.error += 1 ;
  213. } else if(code.startsWith('2')) {
  214. state.responses.success += 1;
  215. } else {
  216. state.responses.other += 1;
  217. }
  218. """,
  219. "combine_script": "state.responses",
  220. "reduce_script": """
  221. def counts = ['error': 0L, 'success': 0L, 'other': 0L];
  222. for (responses in states) {
  223. counts.error += responses['error'];
  224. counts.success += responses['success'];
  225. counts.other += responses['other'];
  226. }
  227. return counts;
  228. """
  229. }
  230. },
  231. "timestamp.min": { "min": { "field": "timestamp" }},
  232. "timestamp.max": { "max": { "field": "timestamp" }},
  233. "timestamp.duration_ms": { <5>
  234. "bucket_script": {
  235. "buckets_path": {
  236. "min_time": "timestamp.min.value",
  237. "max_time": "timestamp.max.value"
  238. },
  239. "script": "(params.max_time - params.min_time)"
  240. }
  241. }
  242. }
  243. }
  244. }
  245. ----------------------------------
  246. // TEST[skip:setup kibana sample data]
  247. <1> This range query limits the {transform} to documents that are within the last
  248. 30 days at the point in time the {transform} checkpoint is processed.
  249. For batch {dataframes} this occurs once.
  250. <2> This is the destination index for the {dataframe}. It is ignored by
  251. `_preview`.
  252. <3> The data is grouped by the `clientip` field.
  253. <4> This `scripted_metric` performs a distributed operation on the web log data
  254. to count specific types of HTTP responses (error, success, and other).
  255. <5> This `bucket_script` calculates the duration of the `clientip` access based
  256. on the results of the aggregation.
  257. The preview shows you that the new index would contain data like this for each
  258. client IP:
  259. [source,js]
  260. ----------------------------------
  261. {
  262. "preview" : [
  263. {
  264. "geo" : {
  265. "src_dc" : 12.0,
  266. "dest_dc" : 9.0
  267. },
  268. "clientip" : "0.72.176.46",
  269. "agent_dc" : 3.0,
  270. "responses" : {
  271. "total" : 14.0,
  272. "counts" : {
  273. "other" : 0,
  274. "success" : 14,
  275. "error" : 0
  276. }
  277. },
  278. "bytes_sum" : 74808.0,
  279. "timestamp" : {
  280. "duration_ms" : 4.919943239E9,
  281. "min" : "2019-06-17T07:51:57.333Z",
  282. "max" : "2019-08-13T06:31:00.572Z"
  283. },
  284. "url_dc" : 11.0
  285. },
  286. ...
  287. }
  288. ----------------------------------
  289. // NOTCONSOLE
  290. This {dataframe} makes it easier to answer questions such as:
  291. * Which client IPs are transferring the most amounts of data?
  292. * Which client IPs are interacting with a high number of different URLs?
  293. * Which client IPs have high error rates?
  294. * Which client IPs are interacting with a high number of destination countries?