Coerce 强制类型转换参数 #
coerce
映射参数控制数据在索引期间如何将其值转换为预期的字段数据类型。此参数让您可以验证数据是否按照预期的字段类型正确格式化和索引。这提高了搜索结果的准确性。
代码样例 #
以下示例演示如何使用 coerce
映射参数。
启用 coerce
去索引文档
#
PUT products
{
"mappings": {
"properties": {
"price": {
"type": "integer",
"coerce": true
}
}
}
}
PUT products/_doc/1
{
"name": "Product A",
"price": "19.99"
}
在此示例中,price
字段被定义为 integer
类型,且 coerce
设置为 true
。在索引文档时,字符串值 19.99
被强制转换为整数 19
。
禁用 coerce
的文档索引
#
PUT orders
{
"mappings": {
"properties": {
"quantity": {
"type": "integer",
"coerce": false
}
}
}
}
PUT orders/_doc/1
{
"item": "Widget",
"quantity": "10"
}
在此示例中,quantity
字段被定义为 integer
类型,且 coerce
设置为 false
。在索引文档时,字符串值 10
不会被强制转换,由于类型不匹配,文档写入会被拒绝。
设置索引级别coerce
强制转换设置
#
PUT inventory
{
"settings": {
"index.mapping.coerce": false
},
"mappings": {
"properties": {
"stock_count": {
"type": "integer",
"coerce": true
},
"sku": {
"type": "keyword"
}
}
}
}
PUT inventory/_doc/1
{
"sku": "ABC123",
"stock_count": "50"
}
在此示例中,索引级别的 index.mapping.coerce
设置为 false
,这会禁用索引的强制转换。但是,stock_count
字段覆盖了此设置,这个字段可以自动转换。