retrieve-selected-fields.asciidoc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. [[search-fields]]
  2. == Retrieve selected fields from a search
  3. ++++
  4. <titleabbrev>Retrieve selected fields</titleabbrev>
  5. ++++
  6. By default, each hit in the search response includes the document
  7. <<mapping-source-field,`_source`>>, which is the entire JSON object that was
  8. provided when indexing the document. To retrieve specific fields in the search
  9. response, you can use the `fields` parameter:
  10. [source,console]
  11. ----
  12. POST my-index-000001/_search
  13. {
  14. "query": {
  15. "match": {
  16. "message": "foo"
  17. }
  18. },
  19. "fields": ["user.id", "@timestamp"],
  20. "_source": false
  21. }
  22. ----
  23. // TEST[setup:my_index]
  24. The `fields` parameter consults both a document's `_source` and the index
  25. mappings to load and return values. Because it makes use of the mappings,
  26. `fields` has some advantages over referencing the `_source` directly: it
  27. accepts <<multi-fields, multi-fields>> and <<alias, field aliases>>, and
  28. also formats field values like dates in a consistent way.
  29. A document's `_source` is stored as a single field in Lucene. So the whole
  30. `_source` object must be loaded and parsed even if only a small number of
  31. fields are requested. To avoid this limitation, you can try another option for
  32. loading fields:
  33. * Use the <<docvalue-fields, `docvalue_fields`>>
  34. parameter to get values for selected fields. This can be a good
  35. choice when returning a fairly small number of fields that support doc values,
  36. such as keywords and dates.
  37. * Use the <<request-body-search-stored-fields, `stored_fields`>> parameter to
  38. get the values for specific stored fields (fields that use the
  39. <<mapping-store,`store`>> mapping option).
  40. You can also use the <<script-fields,`script_field`>> parameter to transform
  41. field values in the response using a script.
  42. You can find more detailed information on each of these methods in the
  43. following sections:
  44. * <<search-fields-param>>
  45. * <<docvalue-fields>>
  46. * <<stored-fields>>
  47. * <<source-filtering>>
  48. * <<script-fields>>
  49. [discrete]
  50. [[search-fields-param]]
  51. === Fields
  52. beta::[]
  53. The `fields` parameter allows for retrieving a list of document fields in
  54. the search response. It consults both the document `_source` and the index
  55. mappings to return each value in a standardized way that matches its mapping
  56. type. By default, date fields are formatted according to the
  57. <<mapping-date-format,date format>> parameter in their mappings.
  58. The following search request uses the `fields` parameter to retrieve values
  59. for the `user.id` field, all fields starting with `http.response.`, and the
  60. `@timestamp` field:
  61. [source,console]
  62. ----
  63. POST my-index-000001/_search
  64. {
  65. "query": {
  66. "match": {
  67. "user.id": "kimchy"
  68. }
  69. },
  70. "fields": [
  71. "user.id",
  72. "http.response.*", <1>
  73. {
  74. "field": "@timestamp",
  75. "format": "epoch_millis" <2>
  76. }
  77. ],
  78. "_source": false
  79. }
  80. ----
  81. // TEST[setup:my_index]
  82. <1> Both full field names and wildcard patterns are accepted.
  83. <2> Using object notation, you can pass a `format` parameter to apply a custom
  84. format for the field's values. The date fields
  85. <<date,`date`>> and <<date_nanos, `date_nanos`>> accept a
  86. <<mapping-date-format,date format>>. <<spatial_datatypes, Spatial fields>>
  87. accept either `geojson` for http://www.geojson.org[GeoJSON] (the default)
  88. or `wkt` for
  89. {wikipedia}/Well-known_text_representation_of_geometry[Well Known Text].
  90. Other field types do not support the `format` parameter.
  91. The values are returned as a flat list in the `fields` section in each hit:
  92. [source,console-result]
  93. ----
  94. {
  95. "took" : 2,
  96. "timed_out" : false,
  97. "_shards" : {
  98. "total" : 1,
  99. "successful" : 1,
  100. "skipped" : 0,
  101. "failed" : 0
  102. },
  103. "hits" : {
  104. "total" : {
  105. "value" : 1,
  106. "relation" : "eq"
  107. },
  108. "max_score" : 1.0,
  109. "hits" : [
  110. {
  111. "_index" : "my-index-000001",
  112. "_id" : "0",
  113. "_score" : 1.0,
  114. "fields" : {
  115. "user.id" : [
  116. "kimchy"
  117. ],
  118. "@timestamp" : [
  119. "4098435132000"
  120. ],
  121. "http.response.bytes": [
  122. 1070000
  123. ],
  124. "http.response.status_code": [
  125. 200
  126. ]
  127. }
  128. }
  129. ]
  130. }
  131. }
  132. ----
  133. // TESTRESPONSE[s/"took" : 2/"took": $body.took/]
  134. // TESTRESPONSE[s/"max_score" : 1.0/"max_score" : $body.hits.max_score/]
  135. // TESTRESPONSE[s/"_score" : 1.0/"_score" : $body.hits.hits.0._score/]
  136. Only leaf fields are returned -- `fields` does not allow for fetching entire
  137. objects.
  138. The `fields` parameter handles field types like <<alias, field aliases>> and
  139. <<constant-keyword-field-type, `constant_keyword`>> whose values aren't always present in
  140. the `_source`. Other mapping options are also respected, including
  141. <<ignore-above, `ignore_above`>>, <<ignore-malformed, `ignore_malformed`>> and
  142. <<null-value, `null_value`>>.
  143. NOTE: The `fields` response always returns an array of values for each field,
  144. even when there is a single value in the `_source`. This is because {es} has
  145. no dedicated array type, and any field could contain multiple values. The
  146. `fields` parameter also does not guarantee that array values are returned in
  147. a specific order. See the mapping documentation on <<array, arrays>> for more
  148. background.
  149. [discrete]
  150. [[search-fields-nested]]
  151. ==== Handling of nested fields
  152. The `fields` response for <<nested,`nested` fields>> is slightly different from that
  153. of regular object fields. While leaf values inside regular `object` fields are
  154. returned as a flat list, values inside `nested` fields are grouped to maintain the
  155. independence of each object inside the original nested array.
  156. For each entry inside a nested field array, values are again returned as a flat list
  157. unless there are other `nested` fields inside the parent nested object, in which case
  158. the same procedure is repeated again for the deeper nested fields.
  159. Given the following mapping where `user` is a nested field, after indexing
  160. the following document and retrieving all fields under the `user` field:
  161. [source,console]
  162. --------------------------------------------------
  163. PUT my-index-000001
  164. {
  165. "mappings": {
  166. "properties": {
  167. "group" : { "type" : "keyword" },
  168. "user": {
  169. "type": "nested",
  170. "properties": {
  171. "first" : { "type" : "keyword" },
  172. "last" : { "type" : "keyword" }
  173. }
  174. }
  175. }
  176. }
  177. }
  178. PUT my-index-000001/_doc/1?refresh=true
  179. {
  180. "group" : "fans",
  181. "user" : [
  182. {
  183. "first" : "John",
  184. "last" : "Smith"
  185. },
  186. {
  187. "first" : "Alice",
  188. "last" : "White"
  189. }
  190. ]
  191. }
  192. POST my-index-000001/_search
  193. {
  194. "fields": ["*"],
  195. "_source": false
  196. }
  197. --------------------------------------------------
  198. the response will group `first` and `last` name instead of
  199. returning them as a flat list.
  200. [source,console-result]
  201. ----
  202. {
  203. "took": 2,
  204. "timed_out": false,
  205. "_shards": {
  206. "total": 1,
  207. "successful": 1,
  208. "skipped": 0,
  209. "failed": 0
  210. },
  211. "hits": {
  212. "total": {
  213. "value": 1,
  214. "relation": "eq"
  215. },
  216. "max_score": 1.0,
  217. "hits": [{
  218. "_index": "my-index-000001",
  219. "_id": "1",
  220. "_score": 1.0,
  221. "fields": {
  222. "group" : ["fans"],
  223. "user": [{
  224. "first": ["John"],
  225. "last": ["Smith"],
  226. },
  227. {
  228. "first": ["Alice"],
  229. "last": ["White"],
  230. }
  231. ]
  232. }
  233. }]
  234. }
  235. }
  236. ----
  237. // TESTRESPONSE[s/"took": 2/"took": $body.took/]
  238. // TESTRESPONSE[s/"max_score" : 1.0/"max_score" : $body.hits.max_score/]
  239. // TESTRESPONSE[s/"_score" : 1.0/"_score" : $body.hits.hits.0._score/]
  240. Nested fields will be grouped by their nested paths, no matter the pattern used to retrieve them.
  241. For example, querying only for the `user.first` field in the example above:
  242. [source,console]
  243. --------------------------------------------------
  244. POST my-index-000001/_search
  245. {
  246. "fields": ["user.first"],
  247. "_source": false
  248. }
  249. --------------------------------------------------
  250. // TEST[continued]
  251. will return only the users first name but still maintain the structure of the nested `user` array:
  252. [source,console-result]
  253. ----
  254. {
  255. "took": 2,
  256. "timed_out": false,
  257. "_shards": {
  258. "total": 1,
  259. "successful": 1,
  260. "skipped": 0,
  261. "failed": 0
  262. },
  263. "hits": {
  264. "total": {
  265. "value": 1,
  266. "relation": "eq"
  267. },
  268. "max_score": 1.0,
  269. "hits": [{
  270. "_index": "my-index-000001",
  271. "_id": "1",
  272. "_score": 1.0,
  273. "fields": {
  274. "user": [{
  275. "first": ["John"],
  276. },
  277. {
  278. "first": ["Alice"],
  279. }
  280. ]
  281. }
  282. }]
  283. }
  284. }
  285. ----
  286. // TESTRESPONSE[s/"took": 2/"took": $body.took/]
  287. // TESTRESPONSE[s/"max_score" : 1.0/"max_score" : $body.hits.max_score/]
  288. // TESTRESPONSE[s/"_score" : 1.0/"_score" : $body.hits.hits.0._score/]
  289. However, when the `fields` pattern targets the nested `user` field directly, no
  290. values will be returned since the pattern doesn't match any leaf fields.
  291. [discrete]
  292. [[retrieve-unmapped-fields]]
  293. ==== Retrieving unmapped fields
  294. By default, the `fields` parameter returns only values of mapped fields. However,
  295. Elasticsearch allows storing fields in `_source` that are unmapped, for example by
  296. setting <<dynamic-field-mapping,Dynamic field mapping>> to `false` or by using an
  297. object field with `enabled: false`, thereby disabling parsing and indexing of its content.
  298. Fields in such an object can be retrieved from `_source` using the `include_unmapped` option
  299. in the `fields` section:
  300. [source,console]
  301. ----
  302. PUT my-index-000001
  303. {
  304. "mappings": {
  305. "enabled": false <1>
  306. }
  307. }
  308. PUT my-index-000001/_doc/1?refresh=true
  309. {
  310. "user_id": "kimchy",
  311. "session_data": {
  312. "object": {
  313. "some_field": "some_value"
  314. }
  315. }
  316. }
  317. POST my-index-000001/_search
  318. {
  319. "fields": [
  320. "user_id",
  321. {
  322. "field": "session_data.object.*",
  323. "include_unmapped" : true <2>
  324. }
  325. ],
  326. "_source": false
  327. }
  328. ----
  329. <1> Disable all mappings.
  330. <2> Include unmapped fields matching this field pattern.
  331. The response will contain fields results under the `session_data.object.*` path even if the
  332. fields are unmapped, but will not contain `user_id` since it is unmapped but the `include_unmapped`
  333. flag hasn't been set to `true` for that field pattern.
  334. [source,console-result]
  335. ----
  336. {
  337. "took" : 2,
  338. "timed_out" : false,
  339. "_shards" : {
  340. "total" : 1,
  341. "successful" : 1,
  342. "skipped" : 0,
  343. "failed" : 0
  344. },
  345. "hits" : {
  346. "total" : {
  347. "value" : 1,
  348. "relation" : "eq"
  349. },
  350. "max_score" : 1.0,
  351. "hits" : [
  352. {
  353. "_index" : "my-index-000001",
  354. "_id" : "1",
  355. "_score" : 1.0,
  356. "fields" : {
  357. "session_data.object.some_field": [
  358. "some_value"
  359. ]
  360. }
  361. }
  362. ]
  363. }
  364. }
  365. ----
  366. // TESTRESPONSE[s/"took" : 2/"took": $body.took/]
  367. // TESTRESPONSE[s/"max_score" : 1.0/"max_score" : $body.hits.max_score/]
  368. // TESTRESPONSE[s/"_score" : 1.0/"_score" : $body.hits.hits.0._score/]
  369. [discrete]
  370. [[docvalue-fields]]
  371. === Doc value fields
  372. You can use the <<docvalue-fields,`docvalue_fields`>> parameter to return
  373. <<doc-values,doc values>> for one or more fields in the search response.
  374. Doc values store the same values as the `_source` but in an on-disk,
  375. column-based structure that's optimized for sorting and aggregations. Since each
  376. field is stored separately, {es} only reads the field values that were requested
  377. and can avoid loading the whole document `_source`.
  378. Doc values are stored for supported fields by default. However, doc values are
  379. not supported for <<text,`text`>> or
  380. {plugins}/mapper-annotated-text-usage.html[`text_annotated`] fields.
  381. The following search request uses the `docvalue_fields` parameter to retrieve
  382. doc values for the `user.id` field, all fields starting with `http.response.`, and the
  383. `@timestamp` field:
  384. [source,console]
  385. ----
  386. GET my-index-000001/_search
  387. {
  388. "query": {
  389. "match": {
  390. "user.id": "kimchy"
  391. }
  392. },
  393. "docvalue_fields": [
  394. "user.id",
  395. "http.response.*", <1>
  396. {
  397. "field": "date",
  398. "format": "epoch_millis" <2>
  399. }
  400. ]
  401. }
  402. ----
  403. // TEST[setup:my_index]
  404. <1> Both full field names and wildcard patterns are accepted.
  405. <2> Using object notation, you can pass a `format` parameter to apply a custom
  406. format for the field's doc values. <<date,Date fields>> support a
  407. <<mapping-date-format,date `format`>>. <<number,Numeric fields>> support a
  408. https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html[DecimalFormat
  409. pattern]. Other field datatypes do not support the `format` parameter.
  410. TIP: You cannot use the `docvalue_fields` parameter to retrieve doc values for
  411. nested objects. If you specify a nested object, the search returns an empty
  412. array (`[ ]`) for the field. To access nested fields, use the
  413. <<inner-hits, `inner_hits`>> parameter's `docvalue_fields`
  414. property.
  415. [discrete]
  416. [[stored-fields]]
  417. === Stored fields
  418. It's also possible to store an individual field's values by using the
  419. <<mapping-store,`store`>> mapping option. You can use the
  420. `stored_fields` parameter to include these stored values in the search response.
  421. WARNING: The `stored_fields` parameter is for fields that are explicitly marked as
  422. stored in the mapping, which is off by default and generally not recommended.
  423. Use <<source-filtering,source filtering>> instead to select
  424. subsets of the original source document to be returned.
  425. Allows to selectively load specific stored fields for each document represented
  426. by a search hit.
  427. [source,console]
  428. --------------------------------------------------
  429. GET /_search
  430. {
  431. "stored_fields" : ["user", "postDate"],
  432. "query" : {
  433. "term" : { "user" : "kimchy" }
  434. }
  435. }
  436. --------------------------------------------------
  437. `*` can be used to load all stored fields from the document.
  438. An empty array will cause only the `_id` and `_type` for each hit to be
  439. returned, for example:
  440. [source,console]
  441. --------------------------------------------------
  442. GET /_search
  443. {
  444. "stored_fields" : [],
  445. "query" : {
  446. "term" : { "user" : "kimchy" }
  447. }
  448. }
  449. --------------------------------------------------
  450. If the requested fields are not stored (`store` mapping set to `false`), they will be ignored.
  451. Stored field values fetched from the document itself are always returned as an array. On the contrary, metadata fields like `_routing` are never returned as an array.
  452. Also only leaf fields can be returned via the `stored_fields` option. If an object field is specified, it will be ignored.
  453. NOTE: On its own, `stored_fields` cannot be used to load fields in nested
  454. objects -- if a field contains a nested object in its path, then no data will
  455. be returned for that stored field. To access nested fields, `stored_fields`
  456. must be used within an <<inner-hits, `inner_hits`>> block.
  457. [discrete]
  458. [[disable-stored-fields]]
  459. ==== Disable stored fields
  460. To disable the stored fields (and metadata fields) entirely use: `_none_`:
  461. [source,console]
  462. --------------------------------------------------
  463. GET /_search
  464. {
  465. "stored_fields": "_none_",
  466. "query" : {
  467. "term" : { "user" : "kimchy" }
  468. }
  469. }
  470. --------------------------------------------------
  471. NOTE: <<source-filtering,`_source`>> and <<request-body-search-version, `version`>> parameters cannot be activated if `_none_` is used.
  472. [discrete]
  473. [[source-filtering]]
  474. === Source filtering
  475. You can use the `_source` parameter to select what fields of the source are
  476. returned. This is called _source filtering_.
  477. The following search API request sets the `_source` request body parameter to
  478. `false`. The document source is not included in the response.
  479. [source,console]
  480. ----
  481. GET /_search
  482. {
  483. "_source": false,
  484. "query": {
  485. "match": {
  486. "user.id": "kimchy"
  487. }
  488. }
  489. }
  490. ----
  491. To return only a subset of source fields, specify a wildcard (`*`) pattern in
  492. the `_source` parameter. The following search API request returns the source for
  493. only the `obj` field and its properties.
  494. [source,console]
  495. ----
  496. GET /_search
  497. {
  498. "_source": "obj.*",
  499. "query": {
  500. "match": {
  501. "user.id": "kimchy"
  502. }
  503. }
  504. }
  505. ----
  506. You can also specify an array of wildcard patterns in the `_source` field. The
  507. following search API request returns the source for only the `obj1` and
  508. `obj2` fields and their properties.
  509. [source,console]
  510. ----
  511. GET /_search
  512. {
  513. "_source": [ "obj1.*", "obj2.*" ],
  514. "query": {
  515. "match": {
  516. "user.id": "kimchy"
  517. }
  518. }
  519. }
  520. ----
  521. For finer control, you can specify an object containing arrays of `includes` and
  522. `excludes` patterns in the `_source` parameter.
  523. If the `includes` property is specified, only source fields that match one of
  524. its patterns are returned. You can exclude fields from this subset using the
  525. `excludes` property.
  526. If the `includes` property is not specified, the entire document source is
  527. returned, excluding any fields that match a pattern in the `excludes` property.
  528. The following search API request returns the source for only the `obj1` and
  529. `obj2` fields and their properties, excluding any child `description` fields.
  530. [source,console]
  531. ----
  532. GET /_search
  533. {
  534. "_source": {
  535. "includes": [ "obj1.*", "obj2.*" ],
  536. "excludes": [ "*.description" ]
  537. },
  538. "query": {
  539. "term": {
  540. "user.id": "kimchy"
  541. }
  542. }
  543. }
  544. ----
  545. [discrete]
  546. [[script-fields]]
  547. === Script fields
  548. You can use the `script_fields` parameter to retrieve a <<modules-scripting,script
  549. evaluation>> (based on different fields) for each hit. For example:
  550. [source,console]
  551. --------------------------------------------------
  552. GET /_search
  553. {
  554. "query": {
  555. "match_all": {}
  556. },
  557. "script_fields": {
  558. "test1": {
  559. "script": {
  560. "lang": "painless",
  561. "source": "doc['price'].value * 2"
  562. }
  563. },
  564. "test2": {
  565. "script": {
  566. "lang": "painless",
  567. "source": "doc['price'].value * params.factor",
  568. "params": {
  569. "factor": 2.0
  570. }
  571. }
  572. }
  573. }
  574. }
  575. --------------------------------------------------
  576. // TEST[setup:sales]
  577. Script fields can work on fields that are not stored (`price` in
  578. the above case), and allow to return custom values to be returned (the
  579. evaluated value of the script).
  580. Script fields can also access the actual `_source` document and
  581. extract specific elements to be returned from it by using `params['_source']`.
  582. Here is an example:
  583. [source,console]
  584. --------------------------------------------------
  585. GET /_search
  586. {
  587. "query" : {
  588. "match_all": {}
  589. },
  590. "script_fields" : {
  591. "test1" : {
  592. "script" : "params['_source']['message']"
  593. }
  594. }
  595. }
  596. --------------------------------------------------
  597. // TEST[setup:my_index]
  598. Note the `_source` keyword here to navigate the json-like model.
  599. It's important to understand the difference between
  600. `doc['my_field'].value` and `params['_source']['my_field']`. The first,
  601. using the doc keyword, will cause the terms for that field to be loaded to
  602. memory (cached), which will result in faster execution, but more memory
  603. consumption. Also, the `doc[...]` notation only allows for simple valued
  604. fields (you can't return a json object from it) and makes sense only for
  605. non-analyzed or single term based fields. However, using `doc` is
  606. still the recommended way to access values from the document, if at all
  607. possible, because `_source` must be loaded and parsed every time it's used.
  608. Using `_source` is very slow.