前言
ignore_malformed是定义Mapping时的一个参数配置,默认为false,即如果将错误的数据类型映射到字段中则会报错,如果设置为true,则可以忽略数据类型的异常。
有时,当你对数据类型不太确定时,可以尝试配置这个属性为true。
演示示例
数值类型
创建一个索引,number_one和number_two两个属性都是integer类型的,但是number_one配置了 “ignore_malformed”: true
PUT my-index-000001
{
"mappings": {
"properties": {
"number_one": {
"type": "integer",
"ignore_malformed": true
},
"number_two": {
"type": "integer"
}
}
}
}
number_one添加一条字符类型的数据,显示添加成功。
PUT my-index-000001/_doc/1
{
"text": "Some text value",
"number_one": "foo"
}
number_two添加一条字符类型的数据,则提示数据类型异常。
PUT my-index-000001/_doc/2
{
"text": "Some text value",
"number_two": "foo"
}
日期类型
同样的操作,date_one犹豫不做格式检查,所以添加一条到毫秒的数据可以添加成功,而date_two则不行。
PUT /my-index-000002
{
"mappings": {
"properties": {
"date_one": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss",
"ignore_malformed": true
},
"date_two": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss"
}
}
}
}
PUT my-index-000002/_doc/1
{ "date_one": "2015-01-01 12:00:00.0" }
PUT my-index-000002/_doc/2
{ "date_two": "2015-01-01 12:00:00.0" }
索引级别配置
ignore_malformed支持在索引级别进行配置,这样默认所有属性都是忽略格式的,但如果属性上又额外配置了ignore_malformed,则按就近原则,以额外配置的为准,比如my-index-000003索引中,number_two依然会检查文档的格式类型。
PUT my-index-000003
{
"settings": {
"index.mapping.ignore_malformed": true
},
"mappings": {
"properties": {
"number_one": {
"type": "byte"
},
"number_two": {
"type": "integer",
"ignore_malformed": false
}
}
}
}
除了支持数值和日期类型之外,ignore_malformed还支持geo、ip,读者可自行尝试。
关于查询
可以看到,当查询所有文档时,不匹配的数据类型可以正常被检索到。
GET /my-index-000001/_search
{
"query": {
"match_all": {}
}
}
当按条件查询时,会提示字段类型错误
GET /my-index-000001/_search
{
"query": {
"match": {
"number_one": "foo"
}
}
}
当插入一条格式类型匹配的文档时,则查询正常。
GET /my-index-000001/_search
{
"query": {
"match": {
"number_one": 3
}
}
}
查询那些格式不匹配的文档
查询所有
GET _search
{
"query": {
"exists": {
"field": "_ignored"
}
}
}
指定查询的字段
GET _search
{
"query": {
"term": {
"_ignored": "number_one"
}
}
}