在实际的使用中,数据并不总是干净的。 根据产生方式的不同,数字可能会在 JSON 主体中呈现为真实的 JSON 数字,例如 5,但也可能呈现为字符串,例如 “5”。 或者,应将应为整数的数字呈现为浮点数,例如 5.0,甚至是 “5.0”。
coerce 尝试清除不匹配的数值以适配字段的数据类型。 例如:
例如:
PUT my_index{ "mappings": { "properties": { "number_one": { "type": "integer" }, "number_two": { "type": "integer", "coerce": false } } }} PUT my_index/_doc/1{ "number_one": "10" } PUT my_index/_doc/2{ "number_two": "10" }
在上面的例子中,我们定义 number_one 为 integer 数据类型,但是它没有属性 coerce 为 false,那么当我们把 number_one 赋值为"10",也就是一个字符串,那么它自动将"10"转换为整型值10。针对第二字段 number_two,它同样被定义为证型值,但是它同时也设置 coerce 为 false,也就是说当字段的值不匹配的时候,就会出现错误。
运行上面的结果是:
可以在索引级别上设置 index.mapping.coerce 设置,以在所有映射类型中全局禁用强制:
PUT my_index{ "settings": { "index.mapping.coerce": false }, "mappings": { "properties": { "number_one": { "type": "integer", "coerce": true }, "number_two": { "type": "integer" } } }} PUT my_index/_doc/1{ "number_one": "10" } PUT my_index/_doc/2{ "number_two": "10" }
上面的运行结果是:
参考:
【1】https://www.elastic.co/guide/en/elasticsearch/reference/current/coerce.html#coerce
包含文章发布时段最新活动,前往ES产品介绍页,可查找ES当前活动统一入口
Elasticsearch Service自建迁移特惠政策>>
Elasticsearch Service 新用户特惠狂欢,最低4折首购优惠 >>
Elasticsearch Service 企业首购特惠,助力企业复工复产>>
关注“腾讯云大数据”公众号,技术交流、最新活动、服务专享一站Get~