Coerce(强制类型转换)
原文链接 :https://www.elastic.co/guide/en/elasticsearch/reference/5.3/coerce.html
数据不总是干净的.根据它的生成方式,一个数字可能会在 JSON body中呈现为一个真正的 JSON 数字。例如5,但它也可能呈现为字符串,例如 “5” 。或者,应该是整型的数字被替代地呈现为浮点型.例如, 5.0 或者 “5.0”.
Coercion 尝试着清理脏数据让字段符合相应的数据类型.例如 :
- 字符串被强制转换为数字.
- 浮点型被截断为整型.
例如 :
curl -XPUT 'localhost:9200/my_index?pretty' -H 'Content-Type: application/json' -d'{"mappings": {"my_type": {"properties": {"number_one": {"type": "integer"},"number_two": {"type": "integer","coerce": false}}}}}'curl -XPUT 'localhost:9200/my_index/my_type/1?pretty' -H 'Content-Type: application/json' -d'{"number_one": "10" (1)}'curl -XPUT 'localhost:9200/my_index/my_type/2?pretty' -H 'Content-Type: application/json' -d'{"number_two": "10" (2)}'
| 1 | number_one 字段会包含整型 10. |
| 2 | document(文档)会拒绝因为coercion是关闭的. |
Tip
coerce 配置允许在相同的索引中具有相同名称的字段有不同的配置.可以通过PUT mapping API来更新已存在字段上的 coerce 值.
Index-level default(索引级别的默认参数)
index.mapping.coerce 配置可以在 index level(索引级别)来设置,以便在所有的 Mapping Types 全局关闭 coercion 配置.
curl -XPUT 'localhost:9200/my_index?pretty' -H 'Content-Type: application/json' -d'{"settings": {"index.mapping.coerce": false},"mappings": {"my_type": {"properties": {"number_one": {"type": "integer","coerce": true},"number_two": {"type": "integer"}}}}}'curl -XPUT 'localhost:9200/my_index/my_type/1?pretty' -H 'Content-Type: application/json' -d'{ "number_one": "10" }(1)'curl -XPUT 'localhost:9200/my_index/my_type/2?pretty' -H 'Content-Type: application/json' -d'{ "number_two": "10" }(2)'
| 1 | number_one 字段覆盖了 index level(索引级别)的设置并开启了 coercion. |
| 2 | document(文档)会拒绝请求,因为 number_two 字段继承了 index-level(索引级别) coercion的设置. |
