coerce.asciidoc 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. [[coerce]]
  2. === `coerce`
  3. Data is not always clean. Depending on how it is produced a number might be
  4. rendered in the JSON body as a true JSON number, e.g. `5`, but it might also
  5. be rendered as a string, e.g. `"5"`. Alternatively, a number that should be
  6. an integer might instead be rendered as a floating point, e.g. `5.0`, or even
  7. `"5.0"`.
  8. Coercion attempts to clean up dirty values to fit the datatype of a field.
  9. For instance:
  10. * Strings will be coerced to numbers.
  11. * Floating points will be truncated for integer values.
  12. For instance:
  13. [source,js]
  14. --------------------------------------------------
  15. PUT my_index
  16. {
  17. "mappings": {
  18. "properties": {
  19. "number_one": {
  20. "type": "integer"
  21. },
  22. "number_two": {
  23. "type": "integer",
  24. "coerce": false
  25. }
  26. }
  27. }
  28. }
  29. PUT my_index/_doc/1
  30. {
  31. "number_one": "10" <1>
  32. }
  33. PUT my_index/_doc/2
  34. {
  35. "number_two": "10" <2>
  36. }
  37. --------------------------------------------------
  38. // CONSOLE
  39. // TEST[catch:bad_request]
  40. <1> The `number_one` field will contain the integer `10`.
  41. <2> This document will be rejected because coercion is disabled.
  42. TIP: The `coerce` setting value can be updated on existing fields
  43. using the <<indices-put-mapping,PUT mapping API>>.
  44. [[coerce-setting]]
  45. ==== Index-level default
  46. The `index.mapping.coerce` setting can be set on the index level to disable
  47. coercion globally across all mapping types:
  48. [source,js]
  49. --------------------------------------------------
  50. PUT my_index
  51. {
  52. "settings": {
  53. "index.mapping.coerce": false
  54. },
  55. "mappings": {
  56. "properties": {
  57. "number_one": {
  58. "type": "integer",
  59. "coerce": true
  60. },
  61. "number_two": {
  62. "type": "integer"
  63. }
  64. }
  65. }
  66. }
  67. PUT my_index/_doc/1
  68. { "number_one": "10" } <1>
  69. PUT my_index/_doc/2
  70. { "number_two": "10" } <2>
  71. --------------------------------------------------
  72. // CONSOLE
  73. // TEST[catch:bad_request]
  74. <1> The `number_one` field overrides the index level setting to enable coercion.
  75. <2> This document will be rejected because the `number_two` field inherits the index-level coercion setting.