common-script-uses.asciidoc 13 KB

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