🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Coerce(强制类型转换) 原文链接 :[https://www.elastic.co/guide/en/elasticsearch/reference/5.3/coerce.html](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](http://www.apache.wiki/pages/createpage-entervariables.action?templateId=4816898&spaceKey=Elasticsearch&title=&newSpaceKey=Elasticsearch&fromPageId=9406602) 贡献者 : [程威](/display/~chengwei),[ApacheCN](/display/~apachecn),[Apache中文网](/display/~apachechina) 数据不总是干净的.根据它的生成方式,一个数字可能会在 **`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](https://www.elastic.co/guide/en/elasticsearch/reference/5.3/indices-put-mapping.html)来更新已存在字段上的 **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`**的设置. |