runtime.asciidoc 46 KB

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