runtime.asciidoc 48 KB

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