runtime.asciidoc 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497
  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-000001/
  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-000001
  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. Runtime fields typically include a Painless script that manipulates data in some
  129. way. However, there are instances where you might define a runtime field
  130. _without_ a script. For example, if you want to retrieve a single field from `_source` without making changes, you don't need a script. You can just create
  131. a runtime field without a script, such as `day_of_week`:
  132. [source,console]
  133. ----
  134. PUT my-index-000001/
  135. {
  136. "mappings": {
  137. "runtime": {
  138. "day_of_week": {
  139. "type": "keyword"
  140. }
  141. }
  142. }
  143. }
  144. ----
  145. When no script is provided, {es} implicitly looks in `_source` at query time
  146. for a field with the same name as the runtime field, and returns a value if one
  147. exists. If a field with the same name doesn’t exist, the response doesn't
  148. include any values for that runtime field.
  149. In most cases, retrieve field values through
  150. <<doc-values,`doc_values`>> whenever possible. Accessing `doc_values` with a
  151. runtime field is faster than retrieving values from `_source` because of how
  152. data is loaded from Lucene.
  153. However, there are cases where retrieving fields from `_source` is necessary.
  154. For example, `text` fields do not have `doc_values` available by default, so you
  155. have to retrieve values from `_source`. In other instances, you might choose to
  156. disable `doc_values` on a specific field.
  157. NOTE: You can alternatively prefix the field you want to retrieve values for
  158. with `params._source` (such as `params._source.day_of_week`). For simplicity,
  159. defining a runtime field in the mapping definition without a script is the
  160. recommended option, whenever possible.
  161. [[runtime-updating-scripts]]
  162. ==== Updating and removing runtime fields
  163. You can update or remove runtime fields at any time. To replace an existing
  164. runtime field, add a new runtime field to the mappings with the same name. To
  165. remove a runtime field from the mappings, set the value of the runtime field to
  166. `null`:
  167. [source,console]
  168. ----
  169. PUT my-index-000001/_mapping
  170. {
  171. "runtime": {
  172. "day_of_week": null
  173. }
  174. }
  175. ----
  176. //TEST[continued]
  177. .Downstream impacts
  178. ****
  179. Updating or removing a runtime field while a dependent query is running can return
  180. inconsistent results. Each shard might have access to different versions of the
  181. script, depending on when the mapping change takes effect.
  182. WARNING: Existing queries or visualizations in {kib} that rely on runtime fields can
  183. fail if you remove or update the field. For example, a bar chart visualization
  184. that uses a runtime field of type `ip` will fail if the type is changed
  185. to `boolean`, or if the runtime field is removed.
  186. ****
  187. [[runtime-search-request]]
  188. === Define runtime fields in a search request
  189. You can specify a `runtime_mappings` section in a search request to create
  190. runtime fields that exist only as part of the query. You specify a script
  191. as part of the `runtime_mappings` section, just as you would if
  192. <<runtime-mapping-fields,adding a runtime field to the mappings>>.
  193. Defining a runtime field in a search request uses the same format as defining
  194. a runtime field in the index mapping. Just copy the field definition from
  195. the `runtime_mappings` in the search request to the `runtime` section of the
  196. index mapping.
  197. The following search request adds a `day_of_week` field to the
  198. `runtime_mappings` section. The field values will be calculated dynamically,
  199. and only within the context of this search request:
  200. [source,console]
  201. ----
  202. GET my-index-000001/_search
  203. {
  204. "runtime_mappings": {
  205. "day_of_week": {
  206. "type": "keyword",
  207. "script": {
  208. "source": "emit(doc['@timestamp'].value.dayOfWeekEnum.getDisplayName(TextStyle.FULL, Locale.ROOT))"
  209. }
  210. }
  211. },
  212. "aggs": {
  213. "day_of_week": {
  214. "terms": {
  215. "field": "day_of_week"
  216. }
  217. }
  218. }
  219. }
  220. ----
  221. //TEST[continued]
  222. [[runtime-search-request-examples]]
  223. [discrete]
  224. === Create runtime fields that use other runtime fields
  225. You can even define runtime fields in a search request that return values from
  226. other runtime fields. For example, let's say you bulk index some sensor data:
  227. [source,console]
  228. ----
  229. POST my-index-000001/_bulk?refresh=true
  230. {"index":{}}
  231. {"@timestamp":1516729294000,"model_number":"QVKC92Q","measures":{"voltage":"5.2","start": "300","end":"8675309"}}
  232. {"index":{}}
  233. {"@timestamp":1516642894000,"model_number":"QVKC92Q","measures":{"voltage":"5.8","start": "300","end":"8675309"}}
  234. {"index":{}}
  235. {"@timestamp":1516556494000,"model_number":"QVKC92Q","measures":{"voltage":"5.1","start": "300","end":"8675309"}}
  236. {"index":{}}
  237. {"@timestamp":1516470094000,"model_number":"QVKC92Q","measures":{"voltage":"5.6","start": "300","end":"8675309"}}
  238. {"index":{}}
  239. {"@timestamp":1516383694000,"model_number":"HG537PU","measures":{"voltage":"4.2","start": "400","end":"8625309"}}
  240. {"index":{}}
  241. {"@timestamp":1516297294000,"model_number":"HG537PU","measures":{"voltage":"4.0","start": "400","end":"8625309"}}
  242. ----
  243. You realize after indexing that your numeric data was mapped as type `text`.
  244. You want to aggregate on the `measures.start` and `measures.end` fields, but
  245. the aggregation fails because you can't aggregate on fields of type `text`.
  246. Runtime fields to the rescue! You can add runtime fields with the same name as
  247. your indexed fields and modify the data type:
  248. [source,console]
  249. ----
  250. PUT my-index-000001/_mapping
  251. {
  252. "runtime": {
  253. "measures.start": {
  254. "type": "long"
  255. },
  256. "measures.end": {
  257. "type": "long"
  258. }
  259. }
  260. }
  261. ----
  262. // TEST[continued]
  263. Runtime fields take precedence over fields defined with the same name in the
  264. index mappings. This flexibility allows you to shadow existing fields and
  265. calculate a different value, without modifying the field itself. If you made a
  266. mistake in your index mapping, you can use runtime fields to calculate values
  267. that <<runtime-override-values,override values>> in the mapping during the
  268. search request.
  269. Now, you can easily run an
  270. <<search-aggregations-metrics-avg-aggregation,average aggregation>> on the
  271. `measures.start` and `measures.end` fields:
  272. [source,console]
  273. ----
  274. GET my-index-000001/_search
  275. {
  276. "aggs": {
  277. "avg_start": {
  278. "avg": {
  279. "field": "measures.start"
  280. }
  281. },
  282. "avg_end": {
  283. "avg": {
  284. "field": "measures.end"
  285. }
  286. }
  287. }
  288. }
  289. ----
  290. // TEST[continued]
  291. // TEST[s/_search/_search\?filter_path=aggregations/]
  292. The response includes the aggregation results without changing the values for
  293. the underlying data:
  294. [source,console-result]
  295. ----
  296. {
  297. "aggregations" : {
  298. "avg_start" : {
  299. "value" : 333.3333333333333
  300. },
  301. "avg_end" : {
  302. "value" : 8658642.333333334
  303. }
  304. }
  305. }
  306. ----
  307. Further, you can define a runtime field as part of a search query that
  308. calculates a value, and then run a
  309. <<search-aggregations-metrics-stats-aggregation,stats aggregation>> on that
  310. field _in the same query_.
  311. The `duration` runtime field doesn't exist in the index mapping, but we can
  312. still search and aggregate on that field. The following query returns the
  313. calculated value for the `duration` field and runs a stats aggregation to
  314. compute statistics over numeric values extracted from the aggregated documents.
  315. [source,console]
  316. ----
  317. GET my-index-000001/_search
  318. {
  319. "runtime_mappings": {
  320. "duration": {
  321. "type": "long",
  322. "script": {
  323. "source": """
  324. emit(doc['measures.end'].value - doc['measures.start'].value);
  325. """
  326. }
  327. }
  328. },
  329. "aggs": {
  330. "duration_stats": {
  331. "stats": {
  332. "field": "duration"
  333. }
  334. }
  335. }
  336. }
  337. ----
  338. // TEST[continued]
  339. // TEST[s/_search/_search\?filter_path=aggregations/]
  340. Even though the `duration` runtime field only exists in the context of a search
  341. query, you can search and aggregate on that field. This flexibility is
  342. incredibly powerful, enabling you to rectify mistakes in your index mappings
  343. and dynamically complete calculations all within a single search request.
  344. [source,console-result]
  345. ----
  346. {
  347. "aggregations" : {
  348. "duration_stats" : {
  349. "count" : 6,
  350. "min" : 8624909.0,
  351. "max" : 8675009.0,
  352. "avg" : 8658309.0,
  353. "sum" : 5.1949854E7
  354. }
  355. }
  356. }
  357. ----
  358. [[runtime-override-values]]
  359. === Override field values at query time
  360. If you create a runtime field with the same name as a field that
  361. already exists in the mapping, the runtime field shadows the mapped field. At
  362. query time, {es} evaluates the runtime field, calculates a value based on the
  363. script, and returns the value as part of the query. Because the runtime field
  364. shadows the mapped field, you can override the value returned in search without
  365. modifying the mapped field.
  366. For example, let's say you indexed the following documents into `my-index-000001`:
  367. [source,console]
  368. ----
  369. POST my-index-000001/_bulk?refresh=true
  370. {"index":{}}
  371. {"@timestamp":1516729294000,"model_number":"QVKC92Q","measures":{"voltage":5.2}}
  372. {"index":{}}
  373. {"@timestamp":1516642894000,"model_number":"QVKC92Q","measures":{"voltage":5.8}}
  374. {"index":{}}
  375. {"@timestamp":1516556494000,"model_number":"QVKC92Q","measures":{"voltage":5.1}}
  376. {"index":{}}
  377. {"@timestamp":1516470094000,"model_number":"QVKC92Q","measures":{"voltage":5.6}}
  378. {"index":{}}
  379. {"@timestamp":1516383694000,"model_number":"HG537PU","measures":{"voltage":4.2}}
  380. {"index":{}}
  381. {"@timestamp":1516297294000,"model_number":"HG537PU","measures":{"voltage":4.0}}
  382. ----
  383. You later realize that the `HG537PU` sensors aren't reporting their true
  384. voltage. The indexed values are supposed to be 1.7 times higher than
  385. the reported values! Instead of reindexing your data, you can define a script in
  386. the `runtime_mappings` section of the `_search` request to shadow the `voltage`
  387. field and calculate a new value at query time.
  388. If you search for documents where the model number matches `HG537PU`:
  389. [source,console]
  390. ----
  391. GET my-index-000001/_search
  392. {
  393. "query": {
  394. "match": {
  395. "model_number": "HG537PU"
  396. }
  397. }
  398. }
  399. ----
  400. //TEST[continued]
  401. The response includes indexed values for documents matching model number
  402. `HG537PU`:
  403. [source,console-result]
  404. ----
  405. {
  406. ...
  407. "hits" : {
  408. "total" : {
  409. "value" : 2,
  410. "relation" : "eq"
  411. },
  412. "max_score" : 1.0296195,
  413. "hits" : [
  414. {
  415. "_index" : "my-index-000001",
  416. "_id" : "F1BeSXYBg_szTodcYCmk",
  417. "_score" : 1.0296195,
  418. "_source" : {
  419. "@timestamp" : 1516383694000,
  420. "model_number" : "HG537PU",
  421. "measures" : {
  422. "voltage" : 4.2
  423. }
  424. }
  425. },
  426. {
  427. "_index" : "my-index-000001",
  428. "_id" : "l02aSXYBkpNf6QRDO62Q",
  429. "_score" : 1.0296195,
  430. "_source" : {
  431. "@timestamp" : 1516297294000,
  432. "model_number" : "HG537PU",
  433. "measures" : {
  434. "voltage" : 4.0
  435. }
  436. }
  437. }
  438. ]
  439. }
  440. }
  441. ----
  442. // TESTRESPONSE[s/\.\.\./"took" : $body.took,"timed_out" : $body.timed_out,"_shards" : $body._shards,/]
  443. // TESTRESPONSE[s/"_id" : "F1BeSXYBg_szTodcYCmk"/"_id": $body.hits.hits.0._id/]
  444. // TESTRESPONSE[s/"_id" : "l02aSXYBkpNf6QRDO62Q"/"_id": $body.hits.hits.1._id/]
  445. The following request defines a runtime field where the script evaluates the
  446. `model_number` field where the value is `HG537PU`. For each match, the script
  447. multiplies the value for the `voltage` field by `1.7`.
  448. Using the <<search-fields,`fields`>> parameter on the `_search` API, you can
  449. retrieve the value that the script calculates for the `measures.voltage` field
  450. for documents matching the search request:
  451. [source,console]
  452. ----
  453. POST my-index-000001/_search
  454. {
  455. "runtime_mappings": {
  456. "measures.voltage": {
  457. "type": "double",
  458. "script": {
  459. "source":
  460. """if (doc['model_number.keyword'].value.equals('HG537PU'))
  461. {emit(1.7 * params._source['measures']['voltage']);}
  462. else{emit(params._source['measures']['voltage']);}"""
  463. }
  464. }
  465. },
  466. "query": {
  467. "match": {
  468. "model_number": "HG537PU"
  469. }
  470. },
  471. "fields": ["measures.voltage"]
  472. }
  473. ----
  474. //TEST[continued]
  475. Looking at the response, the calculated values for `measures.voltage` on each
  476. result are `7.14` and `6.8`. That's more like it! The runtime field calculated
  477. this value as part of the search request without modifying the mapped value,
  478. which still returns in the response:
  479. [source,console-result]
  480. ----
  481. {
  482. ...
  483. "hits" : {
  484. "total" : {
  485. "value" : 2,
  486. "relation" : "eq"
  487. },
  488. "max_score" : 1.0296195,
  489. "hits" : [
  490. {
  491. "_index" : "my-index-000001",
  492. "_id" : "F1BeSXYBg_szTodcYCmk",
  493. "_score" : 1.0296195,
  494. "_source" : {
  495. "@timestamp" : 1516383694000,
  496. "model_number" : "HG537PU",
  497. "measures" : {
  498. "voltage" : 4.2
  499. }
  500. },
  501. "fields" : {
  502. "measures.voltage" : [
  503. 7.14
  504. ]
  505. }
  506. },
  507. {
  508. "_index" : "my-index-000001",
  509. "_id" : "l02aSXYBkpNf6QRDO62Q",
  510. "_score" : 1.0296195,
  511. "_source" : {
  512. "@timestamp" : 1516297294000,
  513. "model_number" : "HG537PU",
  514. "measures" : {
  515. "voltage" : 4.0
  516. }
  517. },
  518. "fields" : {
  519. "measures.voltage" : [
  520. 6.8
  521. ]
  522. }
  523. }
  524. ]
  525. }
  526. }
  527. ----
  528. // TESTRESPONSE[s/\.\.\./"took" : $body.took,"timed_out" : $body.timed_out,"_shards" : $body._shards,/]
  529. // TESTRESPONSE[s/"_id" : "F1BeSXYBg_szTodcYCmk"/"_id": $body.hits.hits.0._id/]
  530. // TESTRESPONSE[s/"_id" : "l02aSXYBkpNf6QRDO62Q"/"_id": $body.hits.hits.1._id/]
  531. [[runtime-retrieving-fields]]
  532. === Retrieve a runtime field
  533. Use the <<search-fields,`fields`>> parameter on the `_search` API to retrieve
  534. the values of runtime fields. Runtime fields won't display in `_source`, but
  535. the `fields` API works for all fields, even those that were not sent as part of
  536. the original `_source`.
  537. [discrete]
  538. [[runtime-define-field-dayofweek]]
  539. ==== Define a runtime field to calculate the day of week
  540. For example, the following request adds a runtime field called `day_of_week`.
  541. The runtime field includes a script that calculates the day of the week based
  542. on the value of the `@timestamp` field. We'll include `"dynamic":"runtime"` in
  543. the request so that new fields are added to the mapping as runtime fields.
  544. [source,console]
  545. ----
  546. PUT my-index-000001/
  547. {
  548. "mappings": {
  549. "dynamic": "runtime",
  550. "runtime": {
  551. "day_of_week": {
  552. "type": "keyword",
  553. "script": {
  554. "source": "emit(doc['@timestamp'].value.dayOfWeekEnum.getDisplayName(TextStyle.FULL, Locale.ROOT))"
  555. }
  556. }
  557. },
  558. "properties": {
  559. "@timestamp": {"type": "date"}
  560. }
  561. }
  562. }
  563. ----
  564. [discrete]
  565. [[runtime-ingest-data]]
  566. ==== Ingest some data
  567. Let's ingest some sample data, which will result in two indexed fields:
  568. `@timestamp` and `message`.
  569. [source,console]
  570. ----
  571. POST /my-index-000001/_bulk?refresh
  572. { "index": {}}
  573. { "@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"}
  574. { "index": {}}
  575. { "@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"}
  576. { "index": {}}
  577. { "@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"}
  578. { "index": {}}
  579. { "@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"}
  580. { "index": {}}
  581. { "@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"}
  582. { "index": {}}
  583. { "@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"}
  584. { "index": {}}
  585. { "@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"}
  586. { "index": {}}
  587. { "@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"}
  588. { "index": {}}
  589. { "@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"}
  590. { "index": {}}
  591. { "@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"}
  592. { "index": {}}
  593. { "@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"}
  594. ----
  595. //TEST[continued]
  596. [discrete]
  597. [[runtime-search-dayofweek]]
  598. ==== Search for the calculated day of week
  599. The following request uses the search API to retrieve the `day_of_week` field
  600. that the original request defined as a runtime field in the mapping. The value
  601. for this field is calculated dynamically at query time without reindexing
  602. documents or indexing the `day_of_week` field. This flexibility allows you to
  603. modify the mapping without changing any field values.
  604. [source,console]
  605. ----
  606. GET my-index-000001/_search
  607. {
  608. "fields": [
  609. "@timestamp",
  610. "day_of_week"
  611. ],
  612. "_source": false
  613. }
  614. ----
  615. // TEST[continued]
  616. The previous request returns the `day_of_week` field for all matching documents.
  617. We can define another runtime field called `client_ip` that also operates on
  618. the `message` field and will further refine the query:
  619. [source,console]
  620. ----
  621. PUT /my-index-000001/_mapping
  622. {
  623. "runtime": {
  624. "client_ip": {
  625. "type": "ip",
  626. "script" : {
  627. "source" : "String m = doc[\"message\"].value; int end = m.indexOf(\" \"); emit(m.substring(0, end));"
  628. }
  629. }
  630. }
  631. }
  632. ----
  633. //TEST[continued]
  634. Run another query, but search for a specific IP address using the `client_ip`
  635. runtime field:
  636. [source,console]
  637. ----
  638. GET my-index-000001/_search
  639. {
  640. "size": 1,
  641. "query": {
  642. "match": {
  643. "client_ip": "211.11.9.0"
  644. }
  645. },
  646. "fields" : ["*"]
  647. }
  648. ----
  649. //TEST[continued]
  650. This time, the response includes only two hits. The value for `day_of_week`
  651. (`Sunday`) was calculated at query time using the runtime script defined in the
  652. mapping, and the result includes only documents matching the `211.11.9.0` IP
  653. address.
  654. [source,console-result]
  655. ----
  656. {
  657. ...
  658. "hits" : {
  659. "total" : {
  660. "value" : 2,
  661. "relation" : "eq"
  662. },
  663. "max_score" : 1.0,
  664. "hits" : [
  665. {
  666. "_index" : "my-index-000001",
  667. "_id" : "oWs5KXYB-XyJbifr9mrz",
  668. "_score" : 1.0,
  669. "_source" : {
  670. "@timestamp" : "2020-06-21T15:00:01-05:00",
  671. "message" : "211.11.9.0 - - [2020-06-21T15:00:01-05:00] \"GET /english/index.html HTTP/1.0\" 304 0"
  672. },
  673. "fields" : {
  674. "@timestamp" : [
  675. "2020-06-21T20:00:01.000Z"
  676. ],
  677. "client_ip" : [
  678. "211.11.9.0"
  679. ],
  680. "message" : [
  681. "211.11.9.0 - - [2020-06-21T15:00:01-05:00] \"GET /english/index.html HTTP/1.0\" 304 0"
  682. ],
  683. "day_of_week" : [
  684. "Sunday"
  685. ]
  686. }
  687. }
  688. ]
  689. }
  690. }
  691. ----
  692. // TESTRESPONSE[s/\.\.\./"took" : $body.took,"timed_out" : $body.timed_out,"_shards" : $body._shards,/]
  693. // TESTRESPONSE[s/"_id" : "oWs5KXYB-XyJbifr9mrz"/"_id": $body.hits.hits.0._id/]
  694. // TESTRESPONSE[s/"day_of_week" : \[\n\s+"Sunday"\n\s\]/"day_of_week": $body.hits.hits.0.fields.day_of_week/]
  695. [[runtime-indexed]]
  696. === Index a runtime field
  697. Runtime fields are defined by the context where they run. For example, you
  698. can define runtime fields in the
  699. <<runtime-search-request,context of a search query>> or within the
  700. <<runtime-mapping-fields,`runtime` section>> of an index mapping. If you
  701. decide to index a runtime field for greater performance, just move the full
  702. runtime field definition (including the script) to the context of an index
  703. mapping. This capability means you can write a script only once, and apply
  704. it to any context that supports runtime fields.
  705. IMPORTANT: After indexing a runtime field, you cannot update the included
  706. script. If you need to change the script, create a new field with the updated
  707. script.
  708. For example, let's say your company wants to replace some old pressure
  709. valves. The connected sensors are only capable of reporting a fraction of
  710. the true readings. Rather than outfit the pressure valves with new sensors,
  711. you decide to calculate the values based on reported readings. Based on the
  712. reported data, you define the following fields in your mapping for
  713. `my-index-000001`:
  714. [source,console]
  715. ----
  716. PUT my-index-000001/
  717. {
  718. "mappings": {
  719. "properties": {
  720. "timestamp": {
  721. "type": "date"
  722. },
  723. "temperature": {
  724. "type": "long"
  725. },
  726. "voltage": {
  727. "type": "double"
  728. },
  729. "node": {
  730. "type": "keyword"
  731. }
  732. }
  733. }
  734. }
  735. ----
  736. You then bulk index some sample data from your sensors. This data includes
  737. `voltage` readings for each sensor:
  738. [source,console]
  739. ----
  740. POST my-index-000001/_bulk?refresh=true
  741. {"index":{}}
  742. {"timestamp": 1516729294000, "temperature": 200, "voltage": 5.2, "node": "a"}
  743. {"index":{}}
  744. {"timestamp": 1516642894000, "temperature": 201, "voltage": 5.8, "node": "b"}
  745. {"index":{}}
  746. {"timestamp": 1516556494000, "temperature": 202, "voltage": 5.1, "node": "a"}
  747. {"index":{}}
  748. {"timestamp": 1516470094000, "temperature": 198, "voltage": 5.6, "node": "b"}
  749. {"index":{}}
  750. {"timestamp": 1516383694000, "temperature": 200, "voltage": 4.2, "node": "c"}
  751. {"index":{}}
  752. {"timestamp": 1516297294000, "temperature": 202, "voltage": 4.0, "node": "c"}
  753. ----
  754. // TEST[continued]
  755. After talking to a few site engineers, you realize that the sensors should
  756. be reporting at least _double_ the current values, but potentially higher.
  757. You create a runtime field named `voltage_corrected` that retrieves the current
  758. voltage and multiplies it by `2`:
  759. [source,console]
  760. ----
  761. PUT my-index-000001/_mapping
  762. {
  763. "runtime": {
  764. "voltage_corrected": {
  765. "type": "double",
  766. "script": {
  767. "source": """
  768. emit(doc['voltage'].value * params['multiplier'])
  769. """,
  770. "params": {
  771. "multiplier": 2
  772. }
  773. }
  774. }
  775. }
  776. }
  777. ----
  778. // TEST[continued]
  779. You retrieve the calculated values using the <<search-fields,`fields`>>
  780. parameter on the `_search` API:
  781. [source,console]
  782. ----
  783. GET my-index-000001/_search
  784. {
  785. "fields": [
  786. "voltage_corrected",
  787. "node"
  788. ],
  789. "size": 2
  790. }
  791. ----
  792. // TEST[continued]
  793. // TEST[s/_search/_search\?filter_path=hits/]
  794. //
  795. ////
  796. [source,console-result]
  797. ----
  798. {
  799. "hits" : {
  800. "total" : {
  801. "value" : 6,
  802. "relation" : "eq"
  803. },
  804. "max_score" : 1.0,
  805. "hits" : [
  806. {
  807. "_index" : "my-index-000001",
  808. "_id" : "z4TCrHgBdg9xpPrU6z9k",
  809. "_score" : 1.0,
  810. "_source" : {
  811. "timestamp" : 1516729294000,
  812. "temperature" : 200,
  813. "voltage" : 5.2,
  814. "node" : "a"
  815. },
  816. "fields" : {
  817. "voltage_corrected" : [
  818. 10.4
  819. ],
  820. "node" : [
  821. "a"
  822. ]
  823. }
  824. },
  825. {
  826. "_index" : "my-index-000001",
  827. "_id" : "0ITCrHgBdg9xpPrU6z9k",
  828. "_score" : 1.0,
  829. "_source" : {
  830. "timestamp" : 1516642894000,
  831. "temperature" : 201,
  832. "voltage" : 5.8,
  833. "node" : "b"
  834. },
  835. "fields" : {
  836. "voltage_corrected" : [
  837. 11.6
  838. ],
  839. "node" : [
  840. "b"
  841. ]
  842. }
  843. }
  844. ]
  845. }
  846. }
  847. ----
  848. // TESTRESPONSE[s/"_id" : "z4TCrHgBdg9xpPrU6z9k"/"_id": $body.hits.hits.0._id/]
  849. // TESTRESPONSE[s/"_id" : "0ITCrHgBdg9xpPrU6z9k"/"_id": $body.hits.hits.1._id/]
  850. ////
  851. //
  852. After reviewing the sensor data and running some tests, you determine that the
  853. multiplier for reported sensor data should be `4`. To gain greater performance,
  854. you decide to index the `voltage_corrected` runtime field with the new
  855. `multiplier` parameter.
  856. In a new index named `my-index-000001`, copy the `voltage_corrected` runtime
  857. field definition into the mappings of the new index. It's that simple! You can
  858. add an optional parameter named `on_script_error` that determines whether to
  859. reject the entire document if the script throws an error at index time
  860. (default).
  861. [source,console]
  862. ----
  863. PUT my-index-000001/
  864. {
  865. "mappings": {
  866. "properties": {
  867. "timestamp": {
  868. "type": "date"
  869. },
  870. "temperature": {
  871. "type": "long"
  872. },
  873. "voltage": {
  874. "type": "double"
  875. },
  876. "node": {
  877. "type": "keyword"
  878. },
  879. "voltage_corrected": {
  880. "type": "double",
  881. "on_script_error": "fail", <1>
  882. "script": {
  883. "source": """
  884. emit(doc['voltage'].value * params['multiplier'])
  885. """,
  886. "params": {
  887. "multiplier": 4
  888. }
  889. }
  890. }
  891. }
  892. }
  893. }
  894. ----
  895. <1> Causes the entire document to be rejected if the script throws an error at
  896. index time. Setting the value to `ignore` will register the field in the
  897. document’s `_ignored` metadata field and continue indexing.
  898. Bulk index some sample data from your sensors into the `my-index-000001` index:
  899. [source,console]
  900. ----
  901. POST my-index-000001/_bulk?refresh=true
  902. { "index": {}}
  903. { "timestamp": 1516729294000, "temperature": 200, "voltage": 5.2, "node": "a"}
  904. { "index": {}}
  905. { "timestamp": 1516642894000, "temperature": 201, "voltage": 5.8, "node": "b"}
  906. { "index": {}}
  907. { "timestamp": 1516556494000, "temperature": 202, "voltage": 5.1, "node": "a"}
  908. { "index": {}}
  909. { "timestamp": 1516470094000, "temperature": 198, "voltage": 5.6, "node": "b"}
  910. { "index": {}}
  911. { "timestamp": 1516383694000, "temperature": 200, "voltage": 4.2, "node": "c"}
  912. { "index": {}}
  913. { "timestamp": 1516297294000, "temperature": 202, "voltage": 4.0, "node": "c"}
  914. ----
  915. // TEST[continued]
  916. You can now retrieve calculated values in a search query, and find documents
  917. based on precise values. The following range query returns all documents where
  918. the calculated `voltage_corrected` is greater than or equal to `10`, but less
  919. than or equal to `16`. Again, use the <<search-fields,`fields`>> parameter on
  920. the `_search` API to retrieve the fields you want:
  921. [source,console]
  922. ----
  923. POST my-index-000001/_search
  924. {
  925. "query": {
  926. "range": {
  927. "voltage_corrected": {
  928. "gte": 16,
  929. "lte": 20,
  930. "boost": 1.0
  931. }
  932. }
  933. },
  934. "fields": [
  935. "voltage_corrected", "node"]
  936. }
  937. ----
  938. // TEST[continued]
  939. // TEST[s/_search/_search\?filter_path=hits/]
  940. The response includes the `voltage_corrected` field for the documents that
  941. match the range query, based on the calculated value of the included script:
  942. [source,console-result]
  943. ----
  944. {
  945. "hits" : {
  946. "total" : {
  947. "value" : 2,
  948. "relation" : "eq"
  949. },
  950. "max_score" : 1.0,
  951. "hits" : [
  952. {
  953. "_index" : "my-index-000001",
  954. "_id" : "yoSLrHgBdg9xpPrUZz_P",
  955. "_score" : 1.0,
  956. "_source" : {
  957. "timestamp" : 1516383694000,
  958. "temperature" : 200,
  959. "voltage" : 4.2,
  960. "node" : "c"
  961. },
  962. "fields" : {
  963. "voltage_corrected" : [
  964. 16.8
  965. ],
  966. "node" : [
  967. "c"
  968. ]
  969. }
  970. },
  971. {
  972. "_index" : "my-index-000001",
  973. "_id" : "y4SLrHgBdg9xpPrUZz_P",
  974. "_score" : 1.0,
  975. "_source" : {
  976. "timestamp" : 1516297294000,
  977. "temperature" : 202,
  978. "voltage" : 4.0,
  979. "node" : "c"
  980. },
  981. "fields" : {
  982. "voltage_corrected" : [
  983. 16.0
  984. ],
  985. "node" : [
  986. "c"
  987. ]
  988. }
  989. }
  990. ]
  991. }
  992. }
  993. ----
  994. // TESTRESPONSE[s/"_id" : "yoSLrHgBdg9xpPrUZz_P"/"_id": $body.hits.hits.0._id/]
  995. // TESTRESPONSE[s/"_id" : "y4SLrHgBdg9xpPrUZz_P"/"_id": $body.hits.hits.1._id/]
  996. [[runtime-examples]]
  997. === Explore your data with runtime fields
  998. Consider a large set of log data that you want to extract fields from.
  999. Indexing the data is time consuming and uses a lot of disk space, and you just
  1000. want to explore the data structure without committing to a schema up front.
  1001. You know that your log data contains specific fields that you want to extract.
  1002. In this case, we want to focus on the `@timestamp` and `message` fields. By
  1003. using runtime fields, you can define scripts to calculate values at search
  1004. time for these fields.
  1005. [[runtime-examples-define-fields]]
  1006. ==== Define indexed fields as a starting point
  1007. You can start with a simple example by adding the `@timestamp` and `message`
  1008. fields to the `my-index-000001` mapping as indexed fields. To remain flexible, use
  1009. `wildcard` as the field type for `message`:
  1010. [source,console]
  1011. ----
  1012. PUT /my-index-000001/
  1013. {
  1014. "mappings": {
  1015. "properties": {
  1016. "@timestamp": {
  1017. "format": "strict_date_optional_time||epoch_second",
  1018. "type": "date"
  1019. },
  1020. "message": {
  1021. "type": "wildcard"
  1022. }
  1023. }
  1024. }
  1025. }
  1026. ----
  1027. [[runtime-examples-ingest-data]]
  1028. ==== Ingest some data
  1029. After mapping the fields you want to retrieve, index a few records from
  1030. your log data into {es}. The following request uses the <<docs-bulk,bulk API>>
  1031. to index raw log data into `my-index-000001`. Instead of indexing all of your log
  1032. data, you can use a small sample to experiment with runtime fields.
  1033. The final document is not a valid Apache log format, but we can account for
  1034. that scenario in our script.
  1035. [source,console]
  1036. ----
  1037. POST /my-index-000001/_bulk?refresh
  1038. {"index":{}}
  1039. {"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"}
  1040. {"index":{}}
  1041. {"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"}
  1042. {"index":{}}
  1043. {"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"}
  1044. {"index":{}}
  1045. {"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"}
  1046. {"index":{}}
  1047. {"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"}
  1048. {"index":{}}
  1049. {"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"}
  1050. {"index":{}}
  1051. {"timestamp":"2020-04-30T14:31:28-05:00","message":"not a valid apache log"}
  1052. ----
  1053. // TEST[continued]
  1054. At this point, you can view how {es} stores your raw data.
  1055. [source,console]
  1056. ----
  1057. GET /my-index-000001
  1058. ----
  1059. // TEST[continued]
  1060. The mapping contains two fields: `@timestamp` and `message`.
  1061. [source,console-result]
  1062. ----
  1063. {
  1064. "my-index-000001" : {
  1065. "aliases" : { },
  1066. "mappings" : {
  1067. "properties" : {
  1068. "@timestamp" : {
  1069. "type" : "date",
  1070. "format" : "strict_date_optional_time||epoch_second"
  1071. },
  1072. "message" : {
  1073. "type" : "wildcard"
  1074. },
  1075. "timestamp" : {
  1076. "type" : "date"
  1077. }
  1078. }
  1079. },
  1080. ...
  1081. }
  1082. }
  1083. ----
  1084. // TESTRESPONSE[s/\.\.\./"settings": $body.my-index-000001.settings/]
  1085. [[runtime-examples-grok]]
  1086. ==== Define a runtime field with a grok pattern
  1087. If you want to retrieve results that include `clientip`, you can add that
  1088. field as a runtime field in the mapping. The following runtime script defines a
  1089. <<grok,grok pattern>> that extracts structured fields out of a single text
  1090. field within a document. A grok pattern is like a regular expression that
  1091. supports aliased expressions that you can reuse.
  1092. The script matches on the `%{COMMONAPACHELOG}` log pattern, which understands
  1093. the structure of Apache logs. If the pattern matches, the script emits the
  1094. value of the matching IP address. If the pattern doesn't match
  1095. (`clientip != null`), the script just returns the field value without crashing.
  1096. [source,console]
  1097. ----
  1098. PUT my-index-000001/_mappings
  1099. {
  1100. "runtime": {
  1101. "http.clientip": {
  1102. "type": "ip",
  1103. "script": """
  1104. String clientip=grok('%{COMMONAPACHELOG}').extract(doc["message"].value)?.clientip;
  1105. if (clientip != null) emit(clientip); <1>
  1106. """
  1107. }
  1108. }
  1109. }
  1110. ----
  1111. // TEST[continued]
  1112. <1> This condition ensures that the script doesn't crash even if the pattern of
  1113. the message doesn't match.
  1114. Alternatively, you can define the same runtime field but in the context of a
  1115. search request. The runtime definition and the script are exactly the same as
  1116. the one defined previously in the index mapping. Just copy that definition into
  1117. the search request under the `runtime_mappings` section and include a query
  1118. that matches on the runtime field. This query returns the same results as if
  1119. you defined a search query for the `http.clientip` runtime field in your index
  1120. mappings, but only in the context of this specific search:
  1121. [source,console]
  1122. ----
  1123. GET my-index-000001/_search
  1124. {
  1125. "runtime_mappings": {
  1126. "http.clientip": {
  1127. "type": "ip",
  1128. "script": """
  1129. String clientip=grok('%{COMMONAPACHELOG}').extract(doc["message"].value)?.clientip;
  1130. if (clientip != null) emit(clientip);
  1131. """
  1132. }
  1133. },
  1134. "query": {
  1135. "match": {
  1136. "http.clientip": "40.135.0.0"
  1137. }
  1138. },
  1139. "fields" : ["http.clientip"]
  1140. }
  1141. ----
  1142. // TEST[continued]
  1143. [[runtime-examples-grok-ip]]
  1144. ===== Search for a specific IP address
  1145. Using the `http.clientip` runtime field, you can define a simple query to run a
  1146. search for a specific IP address and return all related fields.
  1147. [source,console]
  1148. ----
  1149. GET my-index-000001/_search
  1150. {
  1151. "query": {
  1152. "match": {
  1153. "http.clientip": "40.135.0.0"
  1154. }
  1155. },
  1156. "fields" : ["*"]
  1157. }
  1158. ----
  1159. // TEST[continued]
  1160. The API returns the following result. Without building your data structure in
  1161. advance, you can search and explore your data in meaningful ways to experiment
  1162. and determine which fields to index.
  1163. Also, remember that `if` statement in the script?
  1164. [source,painless]
  1165. ----
  1166. if (clientip != null) emit(clientip);
  1167. ----
  1168. If the script didn't include this condition, the query would fail on any shard
  1169. that doesn't match the pattern. By including this condition, the query skips
  1170. data that doesn't match the grok pattern.
  1171. [source,console-result]
  1172. ----
  1173. {
  1174. ...
  1175. "hits" : {
  1176. "total" : {
  1177. "value" : 1,
  1178. "relation" : "eq"
  1179. },
  1180. "max_score" : 1.0,
  1181. "hits" : [
  1182. {
  1183. "_index" : "my-index-000001",
  1184. "_id" : "FdLqu3cBhqheMnFKd0gK",
  1185. "_score" : 1.0,
  1186. "_source" : {
  1187. "timestamp" : "2020-04-30T14:30:17-05:00",
  1188. "message" : "40.135.0.0 - - [30/Apr/2020:14:30:17 -0500] \"GET /images/hm_bg.jpg HTTP/1.0\" 200 24736"
  1189. },
  1190. "fields" : {
  1191. "http.clientip" : [
  1192. "40.135.0.0"
  1193. ],
  1194. "message" : [
  1195. "40.135.0.0 - - [30/Apr/2020:14:30:17 -0500] \"GET /images/hm_bg.jpg HTTP/1.0\" 200 24736"
  1196. ],
  1197. "timestamp" : [
  1198. "2020-04-30T19:30:17.000Z"
  1199. ]
  1200. }
  1201. }
  1202. ]
  1203. }
  1204. }
  1205. ----
  1206. // TESTRESPONSE[s/\.\.\./"took" : $body.took,"timed_out" : $body.timed_out,"_shards" : $body._shards,/]
  1207. // TESTRESPONSE[s/"_id" : "FdLqu3cBhqheMnFKd0gK"/"_id": $body.hits.hits.0._id/]
  1208. [[runtime-examples-grok-range]]
  1209. ===== Search for documents in a specific range
  1210. You can also run a <<query-dsl-range-query,range query>> that operates on the
  1211. `timestamp` field. The following query returns any documents where the
  1212. `timestamp` is greater than or equal to `2020-04-30T14:31:27-05:00`:
  1213. [source,console]
  1214. ----
  1215. GET my-index-000001/_search
  1216. {
  1217. "query": {
  1218. "range": {
  1219. "timestamp": {
  1220. "gte": "2020-04-30T14:31:27-05:00"
  1221. }
  1222. }
  1223. }
  1224. }
  1225. ----
  1226. // TEST[continued]
  1227. The response includes the document where the log format doesn't match, but the
  1228. timestamp falls within the defined range.
  1229. [source,console-result]
  1230. ----
  1231. {
  1232. ...
  1233. "hits" : {
  1234. "total" : {
  1235. "value" : 2,
  1236. "relation" : "eq"
  1237. },
  1238. "max_score" : 1.0,
  1239. "hits" : [
  1240. {
  1241. "_index" : "my-index-000001",
  1242. "_id" : "hdEhyncBRSB6iD-PoBqe",
  1243. "_score" : 1.0,
  1244. "_source" : {
  1245. "timestamp" : "2020-04-30T14:31:27-05:00",
  1246. "message" : "252.0.0.0 - - [30/Apr/2020:14:31:27 -0500] \"GET /images/hm_bg.jpg HTTP/1.0\" 200 24736"
  1247. }
  1248. },
  1249. {
  1250. "_index" : "my-index-000001",
  1251. "_id" : "htEhyncBRSB6iD-PoBqe",
  1252. "_score" : 1.0,
  1253. "_source" : {
  1254. "timestamp" : "2020-04-30T14:31:28-05:00",
  1255. "message" : "not a valid apache log"
  1256. }
  1257. }
  1258. ]
  1259. }
  1260. }
  1261. ----
  1262. // TESTRESPONSE[s/\.\.\./"took" : $body.took,"timed_out" : $body.timed_out,"_shards" : $body._shards,/]
  1263. // TESTRESPONSE[s/"_id" : "hdEhyncBRSB6iD-PoBqe"/"_id": $body.hits.hits.0._id/]
  1264. // TESTRESPONSE[s/"_id" : "htEhyncBRSB6iD-PoBqe"/"_id": $body.hits.hits.1._id/]
  1265. [[runtime-examples-dissect]]
  1266. ==== Define a runtime field with a dissect pattern
  1267. If you don't need the power of regular expressions, you can use
  1268. <<dissect-processor,dissect patterns>> instead of grok patterns. Dissect
  1269. patterns match on fixed delimiters but are typically faster that grok.
  1270. You can use dissect to achieve the same results as parsing the Apache logs with
  1271. a <<runtime-examples-grok,grok pattern>>. Instead of matching on a log
  1272. pattern, you include the parts of the string that you want to discard. Paying
  1273. special attention to the parts of the string you want to discard will help build
  1274. successful dissect patterns.
  1275. [source,console]
  1276. ----
  1277. PUT my-index-000001/_mappings
  1278. {
  1279. "runtime": {
  1280. "http.client.ip": {
  1281. "type": "ip",
  1282. "script": """
  1283. String clientip=dissect('%{clientip} %{ident} %{auth} [%{@timestamp}] "%{verb} %{request} HTTP/%{httpversion}" %{status} %{size}').extract(doc["message"].value)?.clientip;
  1284. if (clientip != null) emit(clientip);
  1285. """
  1286. }
  1287. }
  1288. }
  1289. ----
  1290. // TEST[continued]
  1291. Similarly, you can define a dissect pattern to extract the https://developer.mozilla.org/en-US/docs/Web/HTTP/Status[HTTP response code]:
  1292. [source,console]
  1293. ----
  1294. PUT my-index-000001/_mappings
  1295. {
  1296. "runtime": {
  1297. "http.response": {
  1298. "type": "long",
  1299. "script": """
  1300. String response=dissect('%{clientip} %{ident} %{auth} [%{@timestamp}] "%{verb} %{request} HTTP/%{httpversion}" %{response} %{size}').extract(doc["message"].value)?.response;
  1301. if (response != null) emit(Integer.parseInt(response));
  1302. """
  1303. }
  1304. }
  1305. }
  1306. ----
  1307. // TEST[continued]
  1308. You can then run a query to retrieve a specific HTTP response using the
  1309. `http.response` runtime field:
  1310. [source,console]
  1311. ----
  1312. GET my-index-000001/_search
  1313. {
  1314. "query": {
  1315. "match": {
  1316. "http.response": "304"
  1317. }
  1318. },
  1319. "fields" : ["*"]
  1320. }
  1321. ----
  1322. // TEST[continued]
  1323. The response includes a single document where the HTTP response is `304`:
  1324. [source,console-result]
  1325. ----
  1326. {
  1327. ...
  1328. "hits" : {
  1329. "total" : {
  1330. "value" : 1,
  1331. "relation" : "eq"
  1332. },
  1333. "max_score" : 1.0,
  1334. "hits" : [
  1335. {
  1336. "_index" : "my-index-000001",
  1337. "_id" : "A2qDy3cBWRMvVAuI7F8M",
  1338. "_score" : 1.0,
  1339. "_source" : {
  1340. "timestamp" : "2020-04-30T14:31:22-05:00",
  1341. "message" : "247.37.0.0 - - [30/Apr/2020:14:31:22 -0500] \"GET /images/hm_nbg.jpg HTTP/1.0\" 304 0"
  1342. },
  1343. "fields" : {
  1344. "http.clientip" : [
  1345. "247.37.0.0"
  1346. ],
  1347. "http.response" : [
  1348. 304
  1349. ],
  1350. "message" : [
  1351. "247.37.0.0 - - [30/Apr/2020:14:31:22 -0500] \"GET /images/hm_nbg.jpg HTTP/1.0\" 304 0"
  1352. ],
  1353. "http.client.ip" : [
  1354. "247.37.0.0"
  1355. ],
  1356. "timestamp" : [
  1357. "2020-04-30T19:31:22.000Z"
  1358. ]
  1359. }
  1360. }
  1361. ]
  1362. }
  1363. }
  1364. ----
  1365. // TESTRESPONSE[s/\.\.\./"took" : $body.took,"timed_out" : $body.timed_out,"_shards" : $body._shards,/]
  1366. // TESTRESPONSE[s/"_id" : "A2qDy3cBWRMvVAuI7F8M"/"_id": $body.hits.hits.0._id/]