runtime.asciidoc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. [[runtime]]
  2. == Runtime fields
  3. A _runtime field_ is a field that is evaluated at query time. Runtime fields
  4. enable you to:
  5. * Add fields to existing documents without reindexing your data
  6. * Start working with your data without understanding how it’s structured
  7. * Override the value returned from an indexed field at query time
  8. * Define fields for a specific use without modifying the underlying schema
  9. You access runtime fields from the search API like any other field, and {es}
  10. sees runtime fields no differently. You can define runtime fields in the
  11. <<runtime-mapping-fields,index mapping>> or in the
  12. <<runtime-search-request,search request>>. Your choice, which is part of the
  13. inherent flexibility of runtime fields.
  14. Runtime fields are useful when working with log data
  15. (see <<runtime-examples,examples>>), especially when you're unsure about the
  16. data structure. Your search speed decreases, but your index size is much
  17. smaller and you can more quickly process logs without having to index them.
  18. [discrete]
  19. [[runtime-benefits]]
  20. === Benefits
  21. Because runtime fields aren't indexed, adding a runtime field doesn't increase
  22. the index size. You define runtime fields directly in the index mapping, saving
  23. storage costs and increasing ingestion speed. You can more quickly ingest
  24. data into the Elastic Stack and access it right away. When you define a runtime
  25. field, you can immediately use it in search requests, aggregations, filtering,
  26. and sorting.
  27. If you make a runtime field an indexed field, you don't need to modify any
  28. queries that refer to the runtime field. Better yet, you can refer to some
  29. indices where the field is a runtime field, and other indices where the field
  30. is an indexed field. You have the flexibility to choose which fields to index
  31. and which ones to keep as runtime fields.
  32. At its core, the most important benefit of runtime fields is the ability to
  33. add fields to documents after you've ingested them. This capability simplifies
  34. mapping decisions because you don't have to decide how to parse your data up
  35. front, and can use runtime fields to amend the mapping at any time. Using
  36. runtime fields allows for a smaller index and faster ingest time, which
  37. combined use less resources and reduce your operating costs.
  38. [discrete]
  39. [[runtime-compromises]]
  40. === Compromises
  41. Runtime fields use less disk space and provide flexibility in how you access
  42. your data, but can impact search performance based on the computation defined in
  43. the runtime script.
  44. To balance search performance and flexibility, index fields that you'll
  45. commonly search for and filter on, such as a timestamp. {es} automatically uses
  46. these indexed fields first when running a query, resulting in a fast response
  47. time. You can then use runtime fields to limit the number of fields that {es}
  48. needs to calculate values for. Using indexed fields in tandem with runtime
  49. fields provides flexibility in the data that you index and how you define
  50. queries for other fields.
  51. Use the <<async-search,asynchronous search API>> to run searches that include
  52. runtime fields. This method of search helps to offset the performance impacts
  53. of computing values for runtime fields in each document containing that field.
  54. If the query can't return the result set synchronously, you'll get results
  55. asynchronously as they become available.
  56. IMPORTANT: Queries against runtime fields are considered expensive. If
  57. <<query-dsl-allow-expensive-queries,`search.allow_expensive_queries`>> is set
  58. to `false`, expensive queries are not allowed and {es} will reject any queries
  59. against runtime fields.
  60. [[runtime-mapping-fields]]
  61. === Map a runtime field
  62. You map runtime fields by adding a `runtime` section under the mapping
  63. definition and defining
  64. <<modules-scripting-using,a Painless script>>. This script has access to the
  65. entire context of a document, including the original `_source` and any mapped
  66. fields plus their values. At query time, the script runs and generates values
  67. for each scripted field that is required for the query.
  68. .Emitting runtime field values
  69. ****
  70. When defining a Painless script to use with runtime fields, you must include
  71. the {painless}/painless-runtime-fields-context.html[`emit` method] to emit
  72. calculated values.
  73. ****
  74. For example, the script in the following request calculates the day of the week
  75. from the `@timestamp` field, which is defined as a `date` type. The script
  76. calculates the day of the week based on the value of `timestamp`, and uses
  77. `emit` to return the calculated value.
  78. [source,console]
  79. ----
  80. PUT my-index/
  81. {
  82. "mappings": {
  83. "runtime": {
  84. "day_of_week": {
  85. "type": "keyword",
  86. "script": {
  87. "source": "emit(doc['@timestamp'].value.dayOfWeekEnum.getDisplayName(TextStyle.FULL, Locale.ROOT))"
  88. }
  89. }
  90. },
  91. "properties": {
  92. "@timestamp": {"type": "date"}
  93. }
  94. }
  95. }
  96. ----
  97. The `runtime` section can be any of these data types:
  98. // tag::runtime-data-types[]
  99. * `boolean`
  100. * `date`
  101. * `double`
  102. * `geo_point`
  103. * `ip`
  104. * `keyword`
  105. * `long`
  106. // end::runtime-data-types[]
  107. Runtime fields with a `type` of `date` can accept the
  108. <<mapping-date-format,`format`>> parameter exactly as the `date` field type.
  109. If <<dynamic-field-mapping,dynamic field mapping>> is enabled where the
  110. `dynamic` parameter is set to `runtime`, new fields are automatically added to
  111. the index mapping as runtime fields:
  112. [source,console]
  113. ----
  114. PUT my-index
  115. {
  116. "mappings": {
  117. "dynamic": "runtime",
  118. "properties": {
  119. "@timestamp": {
  120. "type": "date"
  121. }
  122. }
  123. }
  124. }
  125. ----
  126. [[runtime-fields-scriptless]]
  127. ==== Define runtime fields without a script
  128. You can define a runtime field in the mapping definition without a
  129. script. At query time, {es} looks in `_source` for a field with the same name
  130. and returns a value if one exists. If a field with the same name doesn’t
  131. exist, the response doesn't include any values for that runtime field.
  132. [source,console]
  133. ----
  134. PUT my-index/
  135. {
  136. "mappings": {
  137. "runtime": {
  138. "day_of_week": {
  139. "type": "keyword"
  140. }
  141. }
  142. }
  143. }
  144. ----
  145. [[runtime-updating-scripts]]
  146. ==== Updating and removing runtime fields
  147. You can update or remove runtime fields at any time. To replace an existing
  148. runtime field, add a new runtime field to the mappings with the same name. To
  149. remove a runtime field from the mappings, set the value of the runtime field to
  150. `null`:
  151. [source,console]
  152. ----
  153. PUT my-index/_mapping
  154. {
  155. "runtime": {
  156. "day_of_week": null
  157. }
  158. }
  159. ----
  160. //TEST[continued]
  161. .Downstream impacts
  162. ****
  163. Updating or removing a runtime field while a dependent query is running can return
  164. inconsistent results. Each shard might have access to different versions of the
  165. script, depending on when the mapping change takes effect.
  166. Existing queries or visualizations in {kib} that rely on runtime fields can
  167. fail if you remove or update the field. For example, a bar chart visualization
  168. that uses a runtime field of type `ip` will fail if the type is changed
  169. to `boolean`, or if the runtime field is removed.
  170. ****
  171. [[runtime-search-request]]
  172. === Define runtime fields in a search request
  173. You can specify a `runtime_mappings` section in a search request to create
  174. runtime fields that exist only as part of the query. You specify a script
  175. as part of the `runtime_mappings` section, just as you would if adding a
  176. runtime field to the mappings.
  177. Fields defined in the search request take precedence over fields defined with
  178. the same name in the index mappings. This flexibility allows you to shadow
  179. existing fields and calculate a different value in the search request, without
  180. modifying the field itself. If you made a mistake in your index mapping, you
  181. can use runtime fields to calculate values that override values in the mapping
  182. during the search request.
  183. In the following request, the values for the `day_of_week` field are calculated
  184. dynamically, and only within the context of this search request:
  185. [source,console]
  186. ----
  187. GET my-index/_search
  188. {
  189. "runtime_mappings": {
  190. "day_of_week": {
  191. "type": "keyword",
  192. "script": {
  193. "source": "emit(doc['@timestamp'].value.dayOfWeekEnum.getDisplayName(TextStyle.FULL, Locale.ROOT))"
  194. }
  195. }
  196. },
  197. "aggs": {
  198. "day_of_week": {
  199. "terms": {
  200. "field": "day_of_week"
  201. }
  202. }
  203. }
  204. }
  205. ----
  206. //TEST[continued]
  207. Defining a runtime field in a search request uses the same format as defining
  208. a runtime field in the index mapping. That consistency means you can promote a
  209. runtime field from a search request to the index mapping by moving the field
  210. definition from `runtime_mappings` in the search request to the `runtime`
  211. section of the index mapping.
  212. [[runtime-override-values]]
  213. === Override field values at query time
  214. If you create a runtime field with the same name as a field that
  215. already exists in the mapping, the runtime field shadows the mapped field. At
  216. query time, {es} evaluates the runtime field, calculates a value based on the
  217. script, and returns the value as part of the query. Because the runtime field
  218. shadows the mapped field, you can override the value returned in search without
  219. modifying the mapped field.
  220. For example, let's say you indexed the following documents into `my-index`:
  221. [source,console]
  222. ----
  223. POST my-index/_bulk?refresh=true
  224. {"index":{}}
  225. {"@timestamp":1516729294000,"model_number":"QVKC92Q","measures":{"voltage":5.2}}
  226. {"index":{}}
  227. {"@timestamp":1516642894000,"model_number":"QVKC92Q","measures":{"voltage":5.8}}
  228. {"index":{}}
  229. {"@timestamp":1516556494000,"model_number":"QVKC92Q","measures":{"voltage":5.1}}
  230. {"index":{}}
  231. {"@timestamp":1516470094000,"model_number":"QVKC92Q","measures":{"voltage":5.6}}
  232. {"index":{}}
  233. {"@timestamp":1516383694000,"model_number":"HG537PU","measures":{"voltage":4.2}}
  234. {"index":{}}
  235. {"@timestamp":1516297294000,"model_number":"HG537PU","measures":{"voltage":4.0}}
  236. ----
  237. You later realize that the `HG537PU` sensors aren't reporting their true
  238. voltage. The indexed values are supposed to be 1.7 times higher than
  239. the reported values! Instead of reindexing your data, you can define a script in
  240. the `runtime_mappings` section of the `_search` request to shadow the `voltage`
  241. field and calculate a new value at query time.
  242. If you search for documents where the model number matches `HG537PU`:
  243. [source,console]
  244. ----
  245. GET my-index/_search
  246. {
  247. "query": {
  248. "match": {
  249. "model_number": "HG537PU"
  250. }
  251. }
  252. }
  253. ----
  254. //TEST[continued]
  255. The response includes indexed values for documents matching model number
  256. `HG537PU`:
  257. [source,console-result]
  258. ----
  259. {
  260. ...
  261. "hits" : {
  262. "total" : {
  263. "value" : 2,
  264. "relation" : "eq"
  265. },
  266. "max_score" : 1.0296195,
  267. "hits" : [
  268. {
  269. "_index" : "my-index",
  270. "_id" : "F1BeSXYBg_szTodcYCmk",
  271. "_score" : 1.0296195,
  272. "_source" : {
  273. "@timestamp" : 1516383694000,
  274. "model_number" : "HG537PU",
  275. "measures" : {
  276. "voltage" : 4.2
  277. }
  278. }
  279. },
  280. {
  281. "_index" : "my-index",
  282. "_id" : "l02aSXYBkpNf6QRDO62Q",
  283. "_score" : 1.0296195,
  284. "_source" : {
  285. "@timestamp" : 1516297294000,
  286. "model_number" : "HG537PU",
  287. "measures" : {
  288. "voltage" : 4.0
  289. }
  290. }
  291. }
  292. ]
  293. }
  294. }
  295. ----
  296. // TESTRESPONSE[s/\.\.\./"took" : $body.took,"timed_out" : $body.timed_out,"_shards" : $body._shards,/]
  297. // TESTRESPONSE[s/"_id" : "F1BeSXYBg_szTodcYCmk"/"_id": $body.hits.hits.0._id/]
  298. // TESTRESPONSE[s/"_id" : "l02aSXYBkpNf6QRDO62Q"/"_id": $body.hits.hits.1._id/]
  299. The following request defines a runtime field where the script evaluates the
  300. `model_number` field where the value is `HG537PU`. For each match, the script
  301. multiplies the value for the `voltage` field by `1.7`.
  302. Using the <<search-fields,`fields`>> parameter on the `_search` API, you can
  303. retrieve the value that the script calculates for the `measures.voltage` field
  304. for documents matching the search request:
  305. [source,console]
  306. ----
  307. POST my-index/_search
  308. {
  309. "runtime_mappings": {
  310. "measures.voltage": {
  311. "type": "double",
  312. "script": {
  313. "source":
  314. """if (doc['model_number.keyword'].value.equals('HG537PU'))
  315. {emit(1.7 * params._source['measures']['voltage']);}
  316. else{emit(params._source['measures']['voltage']);}"""
  317. }
  318. }
  319. },
  320. "query": {
  321. "match": {
  322. "model_number": "HG537PU"
  323. }
  324. },
  325. "fields": ["measures.voltage"]
  326. }
  327. ----
  328. //TEST[continued]
  329. Looking at the response, the calculated values for `measures.voltage` on each
  330. result are `7.14` and `6.8`. That's more like it! The runtime field calculated
  331. this value as part of the search request without modifying the mapped value,
  332. which still returns in the response:
  333. [source,console-result]
  334. ----
  335. {
  336. ...
  337. "hits" : {
  338. "total" : {
  339. "value" : 2,
  340. "relation" : "eq"
  341. },
  342. "max_score" : 1.0296195,
  343. "hits" : [
  344. {
  345. "_index" : "my-index",
  346. "_id" : "F1BeSXYBg_szTodcYCmk",
  347. "_score" : 1.0296195,
  348. "_source" : {
  349. "@timestamp" : 1516383694000,
  350. "model_number" : "HG537PU",
  351. "measures" : {
  352. "voltage" : 4.2
  353. }
  354. },
  355. "fields" : {
  356. "measures.voltage" : [
  357. 7.14
  358. ]
  359. }
  360. },
  361. {
  362. "_index" : "my-index",
  363. "_id" : "l02aSXYBkpNf6QRDO62Q",
  364. "_score" : 1.0296195,
  365. "_source" : {
  366. "@timestamp" : 1516297294000,
  367. "model_number" : "HG537PU",
  368. "measures" : {
  369. "voltage" : 4.0
  370. }
  371. },
  372. "fields" : {
  373. "measures.voltage" : [
  374. 6.8
  375. ]
  376. }
  377. }
  378. ]
  379. }
  380. }
  381. ----
  382. // TESTRESPONSE[s/\.\.\./"took" : $body.took,"timed_out" : $body.timed_out,"_shards" : $body._shards,/]
  383. // TESTRESPONSE[s/"_id" : "F1BeSXYBg_szTodcYCmk"/"_id": $body.hits.hits.0._id/]
  384. // TESTRESPONSE[s/"_id" : "l02aSXYBkpNf6QRDO62Q"/"_id": $body.hits.hits.1._id/]
  385. [[runtime-retrieving-fields]]
  386. === Retrieve a runtime field
  387. Use the <<search-fields,`fields`>> parameter on the `_search` API to retrieve
  388. the values of runtime fields. Runtime fields won't display in `_source`, but
  389. the `fields` API works for all fields, even those that were not sent as part of
  390. the original `_source`.
  391. [discrete]
  392. [[runtime-define-field-dayofweek]]
  393. ==== Define a runtime field to calculate the day of week
  394. For example, the following request adds a runtime field called `day_of_week`.
  395. The runtime field includes a script that calculates the day of the week based
  396. on the value of the `@timestamp` field. We'll include `"dynamic":"runtime"` in
  397. the request so that new fields are added to the mapping as runtime fields.
  398. [source,console]
  399. ----
  400. PUT my-index/
  401. {
  402. "mappings": {
  403. "dynamic": "runtime",
  404. "runtime": {
  405. "day_of_week": {
  406. "type": "keyword",
  407. "script": {
  408. "source": "emit(doc['@timestamp'].value.dayOfWeekEnum.getDisplayName(TextStyle.FULL, Locale.ROOT))"
  409. }
  410. }
  411. },
  412. "properties": {
  413. "@timestamp": {"type": "date"}
  414. }
  415. }
  416. }
  417. ----
  418. [discrete]
  419. [[runtime-ingest-data]]
  420. ==== Ingest some data
  421. Let's ingest some sample data, which will result in two indexed fields:
  422. `@timestamp` and `message`.
  423. [source,console]
  424. ----
  425. POST /my-index/_bulk?refresh
  426. { "index": {}}
  427. { "@timestamp": "2020-06-21T15:00:01-05:00", "message" : "211.11.9.0 - - [2020-06-21T15:00:01-05:00] \"GET /english/index.html HTTP/1.0\" 304 0"}
  428. { "index": {}}
  429. { "@timestamp": "2020-06-21T15:00:01-05:00", "message" : "211.11.9.0 - - [2020-06-21T15:00:01-05:00] \"GET /english/index.html HTTP/1.0\" 304 0"}
  430. { "index": {}}
  431. { "@timestamp": "2020-04-30T14:30:17-05:00", "message" : "40.135.0.0 - - [2020-04-30T14:30:17-05:00] \"GET /images/hm_bg.jpg HTTP/1.0\" 200 24736"}
  432. { "index": {}}
  433. { "@timestamp": "2020-04-30T14:30:53-05:00", "message" : "232.0.0.0 - - [2020-04-30T14:30:53-05:00] \"GET /images/hm_bg.jpg HTTP/1.0\" 200 24736"}
  434. { "index": {}}
  435. { "@timestamp": "2020-04-30T14:31:12-05:00", "message" : "26.1.0.0 - - [2020-04-30T14:31:12-05:00] \"GET /images/hm_bg.jpg HTTP/1.0\" 200 24736"}
  436. { "index": {}}
  437. { "@timestamp": "2020-04-30T14:31:19-05:00", "message" : "247.37.0.0 - - [2020-04-30T14:31:19-05:00] \"GET /french/splash_inet.html HTTP/1.0\" 200 3781"}
  438. { "index": {}}
  439. { "@timestamp": "2020-04-30T14:31:27-05:00", "message" : "252.0.0.0 - - [2020-04-30T14:31:27-05:00] \"GET /images/hm_bg.jpg HTTP/1.0\" 200 24736"}
  440. { "index": {}}
  441. { "@timestamp": "2020-04-30T14:31:29-05:00", "message" : "247.37.0.0 - - [2020-04-30T14:31:29-05:00] \"GET /images/hm_brdl.gif HTTP/1.0\" 304 0"}
  442. { "index": {}}
  443. { "@timestamp": "2020-04-30T14:31:29-05:00", "message" : "247.37.0.0 - - [2020-04-30T14:31:29-05:00] \"GET /images/hm_arw.gif HTTP/1.0\" 304 0"}
  444. { "index": {}}
  445. { "@timestamp": "2020-04-30T14:31:32-05:00", "message" : "247.37.0.0 - - [2020-04-30T14:31:32-05:00] \"GET /images/nav_bg_top.gif HTTP/1.0\" 200 929"}
  446. { "index": {}}
  447. { "@timestamp": "2020-04-30T14:31:43-05:00", "message" : "247.37.0.0 - - [2020-04-30T14:31:43-05:00] \"GET /french/images/nav_venue_off.gif HTTP/1.0\" 304 0"}
  448. ----
  449. //TEST[continued]
  450. [discrete]
  451. [[runtime-search-dayofweek]]
  452. ==== Search for the calculated day of week
  453. The following request uses the search API to retrieve the `day_of_week` field
  454. that the original request defined as a runtime field in the mapping. The value
  455. for this field is calculated dynamically at query time without reindexing
  456. documents or indexing the `day_of_week` field. This flexibility allows you to
  457. modify the mapping without changing any field values.
  458. [source,console]
  459. ----
  460. GET my-index/_search
  461. {
  462. "fields": [
  463. "@timestamp",
  464. "day_of_week"
  465. ],
  466. "_source": false
  467. }
  468. ----
  469. // TEST[continued]
  470. The previous request returns the `day_of_week` field for all matching documents.
  471. We can define another runtime field called `client_ip` that also operates on
  472. the `message` field and will further refine the query:
  473. [source,console]
  474. ----
  475. PUT /my-index/_mapping
  476. {
  477. "runtime": {
  478. "client_ip": {
  479. "type": "ip",
  480. "script" : {
  481. "source" : "String m = doc[\"message\"].value; int end = m.indexOf(\" \"); emit(m.substring(0, end));"
  482. }
  483. }
  484. }
  485. }
  486. ----
  487. //TEST[continued]
  488. Run another query, but search for a specific IP address using the `client_ip`
  489. runtime field:
  490. [source,console]
  491. ----
  492. GET my-index/_search
  493. {
  494. "size": 1,
  495. "query": {
  496. "match": {
  497. "client_ip": "211.11.9.0"
  498. }
  499. },
  500. "fields" : ["*"]
  501. }
  502. ----
  503. //TEST[continued]
  504. This time, the response includes only two hits. The value for `day_of_week`
  505. (`Sunday`) was calculated at query time using the runtime script defined in the
  506. mapping, and the result includes only documents matching the `211.11.9.0` IP
  507. address.
  508. [source,console-result]
  509. ----
  510. {
  511. ...
  512. "hits" : {
  513. "total" : {
  514. "value" : 2,
  515. "relation" : "eq"
  516. },
  517. "max_score" : 1.0,
  518. "hits" : [
  519. {
  520. "_index" : "my-index",
  521. "_id" : "oWs5KXYB-XyJbifr9mrz",
  522. "_score" : 1.0,
  523. "_source" : {
  524. "@timestamp" : "2020-06-21T15:00:01-05:00",
  525. "message" : "211.11.9.0 - - [2020-06-21T15:00:01-05:00] \"GET /english/index.html HTTP/1.0\" 304 0"
  526. },
  527. "fields" : {
  528. "@timestamp" : [
  529. "2020-06-21T20:00:01.000Z"
  530. ],
  531. "client_ip" : [
  532. "211.11.9.0"
  533. ],
  534. "message" : [
  535. "211.11.9.0 - - [2020-06-21T15:00:01-05:00] \"GET /english/index.html HTTP/1.0\" 304 0"
  536. ],
  537. "day_of_week" : [
  538. "Sunday"
  539. ]
  540. }
  541. }
  542. ]
  543. }
  544. }
  545. ----
  546. // TESTRESPONSE[s/\.\.\./"took" : $body.took,"timed_out" : $body.timed_out,"_shards" : $body._shards,/]
  547. // TESTRESPONSE[s/"_id" : "oWs5KXYB-XyJbifr9mrz"/"_id": $body.hits.hits.0._id/]
  548. // TESTRESPONSE[s/"day_of_week" : \[\n\s+"Sunday"\n\s\]/"day_of_week": $body.hits.hits.0.fields.day_of_week/]
  549. [[runtime-examples]]
  550. === Explore your data with runtime fields
  551. Consider a large set of log data that you want to extract fields from.
  552. Indexing the data is time consuming and uses a lot of disk space, and you just
  553. want to explore the data structure without committing to a schema up front.
  554. You know that your log data contains specific fields that you want to extract.
  555. In this case, we want to focus on the `@timestamp` and `message` fields. By
  556. using runtime fields, you can define scripts to calculate values at search
  557. time for these fields.
  558. [[runtime-examples-define-fields]]
  559. ==== Define indexed fields as a starting point
  560. You can start with a simple example by adding the `@timestamp` and `message`
  561. fields to the `my-index` mapping as indexed fields. To remain flexible, use
  562. `wildcard` as the field type for `message`:
  563. [source,console]
  564. ----
  565. PUT /my-index/
  566. {
  567. "mappings": {
  568. "properties": {
  569. "@timestamp": {
  570. "format": "strict_date_optional_time||epoch_second",
  571. "type": "date"
  572. },
  573. "message": {
  574. "type": "wildcard"
  575. }
  576. }
  577. }
  578. }
  579. ----
  580. [[runtime-examples-ingest-data]]
  581. ==== Ingest some data
  582. After mapping the fields you want to retrieve, index a few records from
  583. your log data into {es}. The following request uses the <<docs-bulk,bulk API>>
  584. to index raw log data into `my-index`. Instead of indexing all of your log
  585. data, you can use a small sample to experiment with runtime fields.
  586. The final document is not a valid Apache log format, but we can account for
  587. that scenario in our script.
  588. [source,console]
  589. ----
  590. POST /my-index/_bulk?refresh
  591. {"index":{}}
  592. {"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"}
  593. {"index":{}}
  594. {"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"}
  595. {"index":{}}
  596. {"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"}
  597. {"index":{}}
  598. {"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"}
  599. {"index":{}}
  600. {"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"}
  601. {"index":{}}
  602. {"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"}
  603. {"index":{}}
  604. {"timestamp":"2020-04-30T14:31:28-05:00","message":"not a valid apache log"}
  605. ----
  606. // TEST[continued]
  607. At this point, you can view how {es} stores your raw data.
  608. [source,console]
  609. ----
  610. GET /my-index
  611. ----
  612. // TEST[continued]
  613. The mapping contains two fields: `@timestamp` and `message`.
  614. [source,console-result]
  615. ----
  616. {
  617. "my-index" : {
  618. "aliases" : { },
  619. "mappings" : {
  620. "properties" : {
  621. "@timestamp" : {
  622. "type" : "date",
  623. "format" : "strict_date_optional_time||epoch_second"
  624. },
  625. "message" : {
  626. "type" : "wildcard"
  627. },
  628. "timestamp" : {
  629. "type" : "date"
  630. }
  631. }
  632. },
  633. ...
  634. }
  635. }
  636. ----
  637. // TESTRESPONSE[s/\.\.\./"settings": $body.my-index.settings/]
  638. [[runtime-examples-grok]]
  639. ==== Define a runtime field with a grok pattern
  640. If you want to retrieve results that include `clientip`, you can add that
  641. field as a runtime field in the mapping. The following runtime script defines a
  642. grok pattern that extracts structured fields out of a single text
  643. field within a document. A grok pattern is like a regular expression that
  644. supports aliased expressions that you can reuse. See <<grok-basics,Grok basics>> to learn more about grok syntax.
  645. The script matches on the `%{COMMONAPACHELOG}` log pattern, which understands
  646. the structure of Apache logs. If the pattern matches, the script emits the
  647. value matching IP address. If the pattern doesn't match
  648. (`clientip != null`), the script just returns the field value without crashing.
  649. [source,console]
  650. ----
  651. PUT my-index/_mappings
  652. {
  653. "runtime": {
  654. "http.clientip": {
  655. "type": "ip",
  656. "script": """
  657. String clientip=grok('%{COMMONAPACHELOG}').extract(doc["message"].value)?.clientip;
  658. if (clientip != null) emit(clientip); <1>
  659. """
  660. }
  661. }
  662. }
  663. ----
  664. // TEST[continued]
  665. <1> This condition ensures that the script doesn't crash even if the pattern of
  666. the message doesn't match.
  667. [[runtime-examples-grok-ip]]
  668. ===== Search for a specific IP address
  669. Using the `http.clientip` runtime field, you can define a simple query to run a
  670. search for a specific IP address and return all related fields.
  671. [source,console]
  672. ----
  673. GET my-index/_search
  674. {
  675. "query": {
  676. "match": {
  677. "http.clientip": "40.135.0.0"
  678. }
  679. },
  680. "fields" : ["*"]
  681. }
  682. ----
  683. // TEST[continued]
  684. The API returns the following result. Without building your data structure in
  685. advance, you can search and explore your data in meaningful ways to experiment
  686. and determine which fields to index.
  687. Also, remember that `if` statement in the script?
  688. [source,painless]
  689. ----
  690. if (clientip != null) emit(clientip);
  691. ----
  692. If the script didn't include this condition, the query would fail on any shard
  693. that doesn't match the pattern. By including this condition, the query skips
  694. data that doesn't match the grok pattern.
  695. [source,console-result]
  696. ----
  697. {
  698. ...
  699. "hits" : {
  700. "total" : {
  701. "value" : 1,
  702. "relation" : "eq"
  703. },
  704. "max_score" : 1.0,
  705. "hits" : [
  706. {
  707. "_index" : "my-index",
  708. "_id" : "FdLqu3cBhqheMnFKd0gK",
  709. "_score" : 1.0,
  710. "_source" : {
  711. "timestamp" : "2020-04-30T14:30:17-05:00",
  712. "message" : "40.135.0.0 - - [30/Apr/2020:14:30:17 -0500] \"GET /images/hm_bg.jpg HTTP/1.0\" 200 24736"
  713. },
  714. "fields" : {
  715. "http.clientip" : [
  716. "40.135.0.0"
  717. ],
  718. "message" : [
  719. "40.135.0.0 - - [30/Apr/2020:14:30:17 -0500] \"GET /images/hm_bg.jpg HTTP/1.0\" 200 24736"
  720. ],
  721. "timestamp" : [
  722. "2020-04-30T19:30:17.000Z"
  723. ]
  724. }
  725. }
  726. ]
  727. }
  728. }
  729. ----
  730. // TESTRESPONSE[s/\.\.\./"took" : $body.took,"timed_out" : $body.timed_out,"_shards" : $body._shards,/]
  731. // TESTRESPONSE[s/"_id" : "FdLqu3cBhqheMnFKd0gK"/"_id": $body.hits.hits.0._id/]
  732. [[runtime-examples-grok-range]]
  733. ===== Search for documents in a specific range
  734. You can also run a <<query-dsl-range-query,range query>> that operates on the
  735. `timestamp` field. The following query returns any documents where the
  736. `timestamp` is greater than or equal to `2020-04-30T14:31:27-05:00`:
  737. [source,console]
  738. ----
  739. GET my-index/_search
  740. {
  741. "query": {
  742. "range": {
  743. "timestamp": {
  744. "gte": "2020-04-30T14:31:27-05:00"
  745. }
  746. }
  747. }
  748. }
  749. ----
  750. // TEST[continued]
  751. The response includes the document where the log format doesn't match, but the
  752. timestamp falls within the defined range.
  753. [source,console-result]
  754. ----
  755. {
  756. ...
  757. "hits" : {
  758. "total" : {
  759. "value" : 2,
  760. "relation" : "eq"
  761. },
  762. "max_score" : 1.0,
  763. "hits" : [
  764. {
  765. "_index" : "my-index",
  766. "_id" : "hdEhyncBRSB6iD-PoBqe",
  767. "_score" : 1.0,
  768. "_source" : {
  769. "timestamp" : "2020-04-30T14:31:27-05:00",
  770. "message" : "252.0.0.0 - - [30/Apr/2020:14:31:27 -0500] \"GET /images/hm_bg.jpg HTTP/1.0\" 200 24736"
  771. }
  772. },
  773. {
  774. "_index" : "my-index",
  775. "_id" : "htEhyncBRSB6iD-PoBqe",
  776. "_score" : 1.0,
  777. "_source" : {
  778. "timestamp" : "2020-04-30T14:31:28-05:00",
  779. "message" : "not a valid apache log"
  780. }
  781. }
  782. ]
  783. }
  784. }
  785. ----
  786. // TESTRESPONSE[s/\.\.\./"took" : $body.took,"timed_out" : $body.timed_out,"_shards" : $body._shards,/]
  787. // TESTRESPONSE[s/"_id" : "hdEhyncBRSB6iD-PoBqe"/"_id": $body.hits.hits.0._id/]
  788. // TESTRESPONSE[s/"_id" : "htEhyncBRSB6iD-PoBqe"/"_id": $body.hits.hits.1._id/]
  789. [[runtime-examples-dissect]]
  790. ==== Define a runtime field with a dissect pattern
  791. If you don't need the power of regular expressions, you can use
  792. <<dissect-processor,dissect patterns>> instead of grok patterns. Dissect
  793. patterns match on fixed delimiters but are typically faster that grok.
  794. You can use dissect to achieve the same results as parsing the Apache logs with
  795. a <<runtime-examples-grok,grok pattern>>. Instead of matching on a log
  796. pattern, you include the parts of the string that you want to discard. Paying
  797. special attention to the parts of the string you want to discard will help build
  798. successful dissect patterns.
  799. [source,console]
  800. ----
  801. PUT my-index/_mappings
  802. {
  803. "runtime": {
  804. "http.client.ip": {
  805. "type": "ip",
  806. "script": """
  807. String clientip=dissect('%{clientip} %{ident} %{auth} [%{@timestamp}] "%{verb} %{request} HTTP/%{httpversion}" %{status} %{size}').extract(doc["message"].value)?.clientip;
  808. if (clientip != null) emit(clientip);
  809. """
  810. }
  811. }
  812. }
  813. ----
  814. // TEST[continued]
  815. Similarly, you can define a dissect pattern to extract the https://developer.mozilla.org/en-US/docs/Web/HTTP/Status[HTTP response code]:
  816. [source,console]
  817. ----
  818. PUT my-index/_mappings
  819. {
  820. "runtime": {
  821. "http.response": {
  822. "type": "long",
  823. "script": """
  824. String response=dissect('%{clientip} %{ident} %{auth} [%{@timestamp}] "%{verb} %{request} HTTP/%{httpversion}" %{response} %{size}').extract(doc["message"].value)?.response;
  825. if (response != null) emit(Integer.parseInt(response));
  826. """
  827. }
  828. }
  829. }
  830. ----
  831. // TEST[continued]
  832. You can then run a query to retrieve a specific HTTP response using the
  833. `http.response` runtime field:
  834. [source,console]
  835. ----
  836. GET my-index/_search
  837. {
  838. "query": {
  839. "match": {
  840. "http.response": "304"
  841. }
  842. },
  843. "fields" : ["*"]
  844. }
  845. ----
  846. // TEST[continued]
  847. The response includes a single document where the HTTP response is `304`:
  848. [source,console-result]
  849. ----
  850. {
  851. ...
  852. "hits" : {
  853. "total" : {
  854. "value" : 1,
  855. "relation" : "eq"
  856. },
  857. "max_score" : 1.0,
  858. "hits" : [
  859. {
  860. "_index" : "my-index",
  861. "_id" : "A2qDy3cBWRMvVAuI7F8M",
  862. "_score" : 1.0,
  863. "_source" : {
  864. "timestamp" : "2020-04-30T14:31:22-05:00",
  865. "message" : "247.37.0.0 - - [30/Apr/2020:14:31:22 -0500] \"GET /images/hm_nbg.jpg HTTP/1.0\" 304 0"
  866. },
  867. "fields" : {
  868. "http.clientip" : [
  869. "247.37.0.0"
  870. ],
  871. "http.response" : [
  872. 304
  873. ],
  874. "message" : [
  875. "247.37.0.0 - - [30/Apr/2020:14:31:22 -0500] \"GET /images/hm_nbg.jpg HTTP/1.0\" 304 0"
  876. ],
  877. "http.client.ip" : [
  878. "247.37.0.0"
  879. ],
  880. "timestamp" : [
  881. "2020-04-30T19:31:22.000Z"
  882. ]
  883. }
  884. }
  885. ]
  886. }
  887. }
  888. ----
  889. // TESTRESPONSE[s/\.\.\./"took" : $body.took,"timed_out" : $body.timed_out,"_shards" : $body._shards,/]
  890. // TESTRESPONSE[s/"_id" : "A2qDy3cBWRMvVAuI7F8M"/"_id": $body.hits.hits.0._id/]