runtime.asciidoc 46 KB

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