common-script-uses.asciidoc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. [[common-script-uses]]
  2. === Common scripting use cases
  3. You can write a script to do almost anything, and sometimes, that's
  4. the trouble. It's challenging to know what's possible with scripts,
  5. so the following examples address common uses cases where scripts are
  6. really helpful.
  7. [[scripting-field-extraction]]
  8. ==== Field extraction
  9. The goal of field extraction is simple; you have fields in your data with a bunch of
  10. information, but you only want to extract pieces and parts.
  11. There are two options at your disposal:
  12. * <<grok-basics,Grok>> is a regular expression dialect that supports aliased
  13. expressions that you can reuse. Because Grok sits on top of regular expressions
  14. (regex), any regular expressions are valid in grok as well.
  15. * <<dissect-processor,Dissect>> extracts structured fields out of text, using
  16. delimiters to define the matching pattern. Unlike grok, dissect doesn't use regular
  17. expressions.
  18. Regex is incredibly powerful but can be complicated. If you don't need the
  19. power of regular expressions, use dissect patterns, which are simple and
  20. often faster than grok patterns. Paying special attention to the parts of the string
  21. you want to discard will help build successful dissect patterns.
  22. Let's start with a simple example by adding the `@timestamp` and `message`
  23. fields to the `my-index` mapping as indexed fields. To remain flexible, use
  24. `wildcard` as the field type for `message`:
  25. [source,console]
  26. ----
  27. PUT /my-index/
  28. {
  29. "mappings": {
  30. "properties": {
  31. "@timestamp": {
  32. "format": "strict_date_optional_time||epoch_second",
  33. "type": "date"
  34. },
  35. "message": {
  36. "type": "wildcard"
  37. }
  38. }
  39. }
  40. }
  41. ----
  42. After mapping the fields you want to retrieve, index a few records from
  43. your log data into {es}. The following request uses the <<docs-bulk,bulk API>>
  44. to index raw log data into `my-index`. Instead of indexing all of your log
  45. data, you can use a small sample to experiment with runtime fields.
  46. [source,console]
  47. ----
  48. POST /my-index/_bulk?refresh
  49. {"index":{}}
  50. {"timestamp":"2020-04-30T14:30:17-05:00","message":"40.135.0.0 - - [30/Apr/2020:14:30:17 -0500] \"GET /images/hm_bg.jpg HTTP/1.0\" 200 24736"}
  51. {"index":{}}
  52. {"timestamp":"2020-04-30T14:30:53-05:00","message":"232.0.0.0 - - [30/Apr/2020:14:30:53 -0500] \"GET /images/hm_bg.jpg HTTP/1.0\" 200 24736"}
  53. {"index":{}}
  54. {"timestamp":"2020-04-30T14:31:12-05:00","message":"26.1.0.0 - - [30/Apr/2020:14:31:12 -0500] \"GET /images/hm_bg.jpg HTTP/1.0\" 200 24736"}
  55. {"index":{}}
  56. {"timestamp":"2020-04-30T14:31:19-05:00","message":"247.37.0.0 - - [30/Apr/2020:14:31:19 -0500] \"GET /french/splash_inet.html HTTP/1.0\" 200 3781"}
  57. {"index":{}}
  58. {"timestamp":"2020-04-30T14:31:22-05:00","message":"247.37.0.0 - - [30/Apr/2020:14:31:22 -0500] \"GET /images/hm_nbg.jpg HTTP/1.0\" 304 0"}
  59. {"index":{}}
  60. {"timestamp":"2020-04-30T14:31:27-05:00","message":"252.0.0.0 - - [30/Apr/2020:14:31:27 -0500] \"GET /images/hm_bg.jpg HTTP/1.0\" 200 24736"}
  61. {"index":{}}
  62. {"timestamp":"2020-04-30T14:31:28-05:00","message":"not a valid apache log"}
  63. ----
  64. // TEST[continued]
  65. [discrete]
  66. [[field-extraction-ip]]
  67. ===== Extract an IP address from a log message (Grok)
  68. If you want to retrieve results that include `clientip`, you can add that
  69. field as a runtime field in the mapping. The following runtime script defines a
  70. grok pattern that extracts structured fields out of the `message` field.
  71. The script matches on the `%{COMMONAPACHELOG}` log pattern, which understands
  72. the structure of Apache logs. If the pattern matches, the script emits the
  73. value matching the IP address. If the pattern doesn't match
  74. (`clientip != null`), the script just returns the field value without crashing.
  75. [source,console]
  76. ----
  77. PUT my-index/_mappings
  78. {
  79. "runtime": {
  80. "http.clientip": {
  81. "type": "ip",
  82. "script": """
  83. String clientip=grok('%{COMMONAPACHELOG}').extract(doc["message"].value)?.clientip;
  84. if (clientip != null) emit(clientip); <1>
  85. """
  86. }
  87. }
  88. }
  89. ----
  90. // TEST[continued]
  91. <1> This condition ensures that the script doesn't emit anything even if the pattern of
  92. the message doesn't match.
  93. You can define a simple query to run a search for a specific IP address and
  94. return all related fields. Use the `fields` parameter of the search API to
  95. retrieve the `http.clientip` runtime field.
  96. [source,console]
  97. ----
  98. GET my-index/_search
  99. {
  100. "query": {
  101. "match": {
  102. "http.clientip": "40.135.0.0"
  103. }
  104. },
  105. "fields" : ["http.clientip"]
  106. }
  107. ----
  108. // TEST[continued]
  109. // TEST[s/_search/_search\?filter_path=hits/]
  110. The response includes documents where the value for `http.clientip` matches
  111. `40.135.0.0`.
  112. [source,console-result]
  113. ----
  114. {
  115. "hits" : {
  116. "total" : {
  117. "value" : 1,
  118. "relation" : "eq"
  119. },
  120. "max_score" : 1.0,
  121. "hits" : [
  122. {
  123. "_index" : "my-index",
  124. "_id" : "Rq-ex3gBA_A0V6dYGLQ7",
  125. "_score" : 1.0,
  126. "_source" : {
  127. "timestamp" : "2020-04-30T14:30:17-05:00",
  128. "message" : "40.135.0.0 - - [30/Apr/2020:14:30:17 -0500] \"GET /images/hm_bg.jpg HTTP/1.0\" 200 24736"
  129. },
  130. "fields" : {
  131. "http.clientip" : [
  132. "40.135.0.0"
  133. ]
  134. }
  135. }
  136. ]
  137. }
  138. }
  139. ----
  140. // TESTRESPONSE[s/"_id" : "Rq-ex3gBA_A0V6dYGLQ7"/"_id": $body.hits.hits.0._id/]
  141. [discrete]
  142. [[field-extraction-parse]]
  143. ==== Parse a string to extract part of a field (Dissect)
  144. Instead of matching on a log pattern like in the <<field-extraction-ip,previous example>>, you can just define a dissect pattern to include the parts of the string
  145. that you want to discard.
  146. For example, the log data at the start of this section includes a `message`
  147. field. This field contains several pieces of data:
  148. [source,js]
  149. ----
  150. "message" : "247.37.0.0 - - [30/Apr/2020:14:31:22 -0500] \"GET /images/hm_nbg.jpg HTTP/1.0\" 304 0"
  151. ----
  152. // NOTCONSOLE
  153. You can define a dissect pattern in a runtime field to extract the https://developer.mozilla.org/en-US/docs/Web/HTTP/Status[HTTP response code], which is
  154. `304` in the previous example.
  155. [source,console]
  156. ----
  157. PUT my-index/_mappings
  158. {
  159. "runtime": {
  160. "http.response": {
  161. "type": "long",
  162. "script": """
  163. String response=dissect('%{clientip} %{ident} %{auth} [%{@timestamp}] "%{verb} %{request} HTTP/%{httpversion}" %{response} %{size}').extract(doc["message"].value)?.response;
  164. if (response != null) emit(Integer.parseInt(response));
  165. """
  166. }
  167. }
  168. }
  169. ----
  170. // TEST[continued]
  171. You can then run a query to retrieve a specific HTTP response using the
  172. `http.response` runtime field:
  173. [source,console]
  174. ----
  175. GET my-index/_search
  176. {
  177. "query": {
  178. "match": {
  179. "http.response": "304"
  180. }
  181. },
  182. "fields" : ["http.response"]
  183. }
  184. ----
  185. // TEST[continued]
  186. // TEST[s/_search/_search\?filter_path=hits/]
  187. The response includes a single document where the HTTP response is `304`:
  188. [source,console-result]
  189. ----
  190. {
  191. "hits" : {
  192. "total" : {
  193. "value" : 1,
  194. "relation" : "eq"
  195. },
  196. "max_score" : 1.0,
  197. "hits" : [
  198. {
  199. "_index" : "my-index",
  200. "_id" : "Sq-ex3gBA_A0V6dYGLQ7",
  201. "_score" : 1.0,
  202. "_source" : {
  203. "timestamp" : "2020-04-30T14:31:22-05:00",
  204. "message" : "247.37.0.0 - - [30/Apr/2020:14:31:22 -0500] \"GET /images/hm_nbg.jpg HTTP/1.0\" 304 0"
  205. },
  206. "fields" : {
  207. "http.response" : [
  208. 304
  209. ]
  210. }
  211. }
  212. ]
  213. }
  214. }
  215. ----
  216. // TESTRESPONSE[s/"_id" : "Sq-ex3gBA_A0V6dYGLQ7"/"_id": $body.hits.hits.0._id/]
  217. [discrete]
  218. [[field-extraction-split]]
  219. ==== Split values in a field by a separator (Dissect)
  220. Let's say you want to extract part of a field like in the previous example, but you
  221. want to split on specific values. You can use a dissect pattern to extract only the
  222. information that you want, and also return that data in a specific format.
  223. For example, let's say you have a bunch of garbage collection (gc) log data from {es}
  224. in this format:
  225. [source,txt]
  226. ----
  227. [2021-04-27T16:16:34.699+0000][82460][gc,heap,exit] class space used 266K, capacity 384K, committed 384K, reserved 1048576K
  228. ----
  229. // NOTCONSOLE
  230. You only want to extract the `used`, `capacity`, and `committed` data, along with
  231. the associated values. Let's index some a few documents containing log data to use as
  232. an example:
  233. [source,console]
  234. ----
  235. POST /my-index/_bulk?refresh
  236. {"index":{}}
  237. {"gc": "[2021-04-27T16:16:34.699+0000][82460][gc,heap,exit] class space used 266K, capacity 384K, committed 384K, reserved 1048576K"}
  238. {"index":{}}
  239. {"gc": "[2021-03-24T20:27:24.184+0000][90239][gc,heap,exit] class space used 15255K, capacity 16726K, committed 16844K, reserved 1048576K"}
  240. {"index":{}}
  241. {"gc": "[2021-03-24T20:27:24.184+0000][90239][gc,heap,exit] Metaspace used 115409K, capacity 119541K, committed 120248K, reserved 1153024K"}
  242. {"index":{}}
  243. {"gc": "[2021-04-19T15:03:21.735+0000][84408][gc,heap,exit] class space used 14503K, capacity 15894K, committed 15948K, reserved 1048576K"}
  244. {"index":{}}
  245. {"gc": "[2021-04-19T15:03:21.735+0000][84408][gc,heap,exit] Metaspace used 107719K, capacity 111775K, committed 112724K, reserved 1146880K"}
  246. {"index":{}}
  247. {"gc": "[2021-04-27T16:16:34.699+0000][82460][gc,heap,exit] class space used 266K, capacity 367K, committed 384K, reserved 1048576K"}
  248. ----
  249. Looking at the data again, there's a timestamp, some other data that you're not
  250. interested in, and then the `used`, `capacity`, and `committed` data:
  251. [source,txt]
  252. ----
  253. [2021-04-27T16:16:34.699+0000][82460][gc,heap,exit] class space used 266K, capacity 384K, committed 384K, reserved 1048576K
  254. ----
  255. You can assign variables to each part of the data in the `gc` field, and then return
  256. only the parts that you want. Anything in curly braces `{}` is considered a variable.
  257. For example, the variables `[%{@timestamp}][%{code}][%{desc}]` will match the first
  258. three chunks of data, all of which are in square brackets `[]`.
  259. [source,txt]
  260. ----
  261. [%{@timestamp}][%{code}][%{desc}] %{ident} used %{usize}, capacity %{csize}, committed %{comsize}, reserved %{rsize}
  262. ----
  263. Your dissect pattern can include the terms `used`, `capacity`, and `committed` instead
  264. of using variables, because you want to return those terms exactly. You also assign
  265. variables to the values you want to return, such as `%{usize}`, `%{csize}`, and
  266. `%{comsize}`. The separator in the log data is a comma, so your dissect pattern also
  267. needs to use that separator.
  268. Now that you have a dissect pattern, you can include it in a Painless script as part
  269. of a runtime field. The script uses your dissect pattern to split apart the `gc`
  270. field, and then returns exactly the information that you want as defined by the
  271. `emit` method. Because dissect uses simple syntax, you just need to tell it exactly
  272. what you want.
  273. The following pattern tells dissect to return the term `used`, a blank space, the value
  274. from `gc.usize`, and a comma. This pattern repeats for the other data that you
  275. want to retrieve. While this pattern might not be as useful in production, it provides
  276. a lot of flexibility to experiment with and manipulate your data. In a production
  277. setting, you might just want to use `emit(gc.usize)` and then aggregate on that value
  278. or use it in computations.
  279. [source,painless]
  280. ----
  281. emit("used" + ' ' + gc.usize + ', ' + "capacity" + ' ' + gc.csize + ', ' + "committed" + ' ' + gc.comsize)
  282. ----
  283. Putting it all together, you can create a runtime field named `gc_size` in a search
  284. request. Using the <<search-fields-param,`fields` option>>, you can retrieve all values
  285. for the `gc_size` runtime field. This query also includes a bucket aggregation to group
  286. your data.
  287. [source,console]
  288. ----
  289. GET my-index/_search
  290. {
  291. "runtime_mappings": {
  292. "gc_size": {
  293. "type": "keyword",
  294. "script": """
  295. Map gc=dissect('[%{@timestamp}][%{code}][%{desc}] %{ident} used %{usize}, capacity %{csize}, committed %{comsize}, reserved %{rsize}').extract(doc["gc.keyword"].value);
  296. if (gc != null) emit("used" + ' ' + gc.usize + ', ' + "capacity" + ' ' + gc.csize + ', ' + "committed" + ' ' + gc.comsize);
  297. """
  298. }
  299. },
  300. "size": 1,
  301. "aggs": {
  302. "sizes": {
  303. "terms": {
  304. "field": "gc_size",
  305. "size": 10
  306. }
  307. }
  308. },
  309. "fields" : ["gc_size"]
  310. }
  311. ----
  312. // TEST[continued]
  313. The response includes the data from the `gc_size` field, formatted exactly as you
  314. defined it in the dissect pattern!
  315. [source,console-result]
  316. ----
  317. {
  318. "took" : 2,
  319. "timed_out" : false,
  320. "_shards" : {
  321. "total" : 1,
  322. "successful" : 1,
  323. "skipped" : 0,
  324. "failed" : 0
  325. },
  326. "hits" : {
  327. "total" : {
  328. "value" : 6,
  329. "relation" : "eq"
  330. },
  331. "max_score" : 1.0,
  332. "hits" : [
  333. {
  334. "_index" : "my-index",
  335. "_id" : "GXx3H3kBKGE42WRNlddJ",
  336. "_score" : 1.0,
  337. "_source" : {
  338. "gc" : "[2021-04-27T16:16:34.699+0000][82460][gc,heap,exit] class space used 266K, capacity 384K, committed 384K, reserved 1048576K"
  339. },
  340. "fields" : {
  341. "gc_size" : [
  342. "used 266K, capacity 384K, committed 384K"
  343. ]
  344. }
  345. }
  346. ]
  347. },
  348. "aggregations" : {
  349. "sizes" : {
  350. "doc_count_error_upper_bound" : 0,
  351. "sum_other_doc_count" : 0,
  352. "buckets" : [
  353. {
  354. "key" : "used 107719K, capacity 111775K, committed 112724K",
  355. "doc_count" : 1
  356. },
  357. {
  358. "key" : "used 115409K, capacity 119541K, committed 120248K",
  359. "doc_count" : 1
  360. },
  361. {
  362. "key" : "used 14503K, capacity 15894K, committed 15948K",
  363. "doc_count" : 1
  364. },
  365. {
  366. "key" : "used 15255K, capacity 16726K, committed 16844K",
  367. "doc_count" : 1
  368. },
  369. {
  370. "key" : "used 266K, capacity 367K, committed 384K",
  371. "doc_count" : 1
  372. },
  373. {
  374. "key" : "used 266K, capacity 384K, committed 384K",
  375. "doc_count" : 1
  376. }
  377. ]
  378. }
  379. }
  380. }
  381. ----
  382. // TESTRESPONSE[s/"took" : 2/"took": "$body.took"/]
  383. // TESTRESPONSE[s/"_id" : "GXx3H3kBKGE42WRNlddJ"/"_id": $body.hits.hits.0._id/]