Elasticsearch:Elasticsearch中的数据强制匹配

在实际的使用中,数据并不总是干净的。 根据产生方式的不同,数字可能会在JSON主体中呈现为真实的JSON数字,例如 5,但也可能呈现为字符串,例如 “5”。 或者,应将应为整数的数字呈现为浮点数,例如 5.0,甚至是“5.0”。

coerce尝试清除不匹配的数值以适配字段的数据类型。 例如:

  • 字符串将被强制转换为数字,比如"5"转换为整型数值5
  • 浮点将被截断为整数值,比如5.0转换为整型值5

例如:

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,也就是说当字段的值不匹配的时候,就会出现错误。

运行上面的结果是:

  • number_one字段将包含整数10。
  • 由于禁用了强制,因此该文档将被拒绝

Index级默认设置

可以在索引级别上设置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" } 

上面的运行结果是:

  • number_one字段将覆盖索引级别设置以启用强制。该文档将被接受
  • 该文档将被拒绝,因为number_two继承了索引级强制设置。

参考:

【1】https://www.elastic.co/guide/en/elasticsearch/reference/current/coerce.html#coerce

发布了489 篇原创文章 · 获赞 107 · 访问量 84万+

猜你喜欢

转载自blog.csdn.net/UbuntuTouch/article/details/104091682