Coerce(强制类型转换)

原文链接 :https://www.elastic.co/guide/en/elasticsearch/reference/5.3/coerce.html

译文链接 : http://www.apache.wiki/pages/createpage-entervariables.action?templateId=4816898&spaceKey=Elasticsearch&title=&newSpaceKey=Elasticsearch&fromPageId=9406602

贡献者 : 程威ApacheCNApache中文网

数据不总是干净的.根据它的生成方式,一个数字可能会在 JSON body中呈现为一个真正的 JSON 数字。例如5,但它也可能呈现为字符串,例如 “5” 。或者,应该是整型的数字被替代地呈现为浮点型.例如, 5.0 或者 “5.0”.

Coercion 尝试着清理脏数据让字段符合相应的数据类型.例如 :

  • 字符串被强制转换为数字.
  • 浮点型被截断为整型.

例如 :

  1. curl -XPUT 'localhost:9200/my_index?pretty' -H 'Content-Type: application/json' -d'
  2. {
  3. "mappings": {
  4. "my_type": {
  5. "properties": {
  6. "number_one": {
  7. "type": "integer"
  8. },
  9. "number_two": {
  10. "type": "integer",
  11. "coerce": false
  12. }
  13. }
  14. }
  15. }
  16. }
  17. '
  18. curl -XPUT 'localhost:9200/my_index/my_type/1?pretty' -H 'Content-Type: application/json' -d'
  19. {
  20. "number_one": "10" (1)
  21. }
  22. '
  23. curl -XPUT 'localhost:9200/my_index/my_type/2?pretty' -H 'Content-Type: application/json' -d'
  24. {
  25. "number_two": "10" (2)
  26. }
  27. '

| 1 | number_one 字段会包含整型 10. | | 2 | document(文档)会拒绝因为coercion是关闭的. |

Tip

coerce 配置允许在相同的索引中具有相同名称的字段有不同的配置.可以通过PUT mapping API来更新已存在字段上的 coerce 值.

Index-level default(索引级别的默认参数)

index.mapping.coerce 配置可以在 index level(索引级别)来设置,以便在所有的 Mapping Types 全局关闭 coercion 配置.

  1. curl -XPUT 'localhost:9200/my_index?pretty' -H 'Content-Type: application/json' -d'
  2. {
  3. "settings": {
  4. "index.mapping.coerce": false
  5. },
  6. "mappings": {
  7. "my_type": {
  8. "properties": {
  9. "number_one": {
  10. "type": "integer",
  11. "coerce": true
  12. },
  13. "number_two": {
  14. "type": "integer"
  15. }
  16. }
  17. }
  18. }
  19. }
  20. '
  21. curl -XPUT 'localhost:9200/my_index/my_type/1?pretty' -H 'Content-Type: application/json' -d'
  22. { "number_one": "10" }(1)
  23. '
  24. curl -XPUT 'localhost:9200/my_index/my_type/2?pretty' -H 'Content-Type: application/json' -d'
  25. { "number_two": "10" }(2)
  26. '

| 1 | number_one 字段覆盖了 index level(索引级别)的设置并开启了 coercion. | | 2 | document(文档)会拒绝请求,因为 number_two 字段继承了 index-level(索引级别) coercion的设置. |