Link Search Menu Expand Document Documentation Menu

强制转换

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 字段会覆盖此设置并为此特定字段启用强制转换。

剩余 350 字符

有问题?

想要贡献?