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 不会被强制转换,并且由于类型不匹配,文档会被拒绝。
设置索引级别的强制转换设置
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 字段覆盖了此设置,并为该特定字段启用了强制转换。