Dynamic field mapping(动态字段映射)

默认情况下,当文档中找到以前未出现过的字段时,Elasticsearch会将新的字段添加到类型映射中。这个行为可以被禁用,通过文档和对象级别上去将动态参数设置为false(忽略新的字段)或采用严谨的格式(在遇到未知字段时抛出异常)来禁用该行为。

假设启用了动态字段映射,则使用一些简单的规则来确定该字段应有的数据类型:

JSON datatype(JSON数据类型)

Elasticsearch datatype(Elasticsearch数据类型)

null

空!没有添加数据

true OR false

boolean字段(布尔类型字段)

floating point number(浮点型数字)

float字段(浮点类型字段)

integer

long字段(长整型字段)

object

对象字段(对象类型字段)

array

数组字段.(具体类型取决于数组中的第一个非空值)

string

要么是date字段(值通过日期检测),要么是double或long型字段(值通过数据检测),要么是文本字段,与keyword子字段。

有这些字段类型可以动态检测出来。因此,必须明确定义其他数据类型。

除了以下列出的选项,动态字段映射规则也可以通过dynamic_templates(动态模板)进一步定制。

Date detection(日期检测)

如果启动date_detection(默认),则会检查新的字符串字段,查看其内容是否与dynamic_date_formats中任一日期模式匹配。如果发现匹配,则添加一个相应格式的新的日期字段。

dynamic_date_formats的默认值为:

[ "strict_date_optional_time","yyyy/MM/dd HH:mm:ss Z||yyyy/MM/dd Z"]

例子:

PUT my_index/my_type/1
{
  "create_date": "2015/09/02"
}

GET my_index/_mapping  # 1

1

create_date字段已经添加成格式为"yyyy/MM/dd HH:mm:ss Z||yyyy/MM/dd Z"的日期字段

Disabling date detection(禁用日期检测)

可以通过将date_detection设置为false来禁用动态日期检测:

PUT my_index
{
  "mappings": {
    "my_type": {
      "date_detection": false
    }
  }
}

PUT my_index/my_type/1   # 1
{
  "create": "2015/09/02"
}

1

create_date字段已添加为text(文本)字段。

Customising detected date formats(自定义检测到的日期格式)

或者,可以通过自定义dynamic_date_formats来支持你自己的日期格式:

PUT my_index
{
  "mappings": {
    "my_type": {
      "dynamic_date_formats": ["MM/dd/yyyy"]
    }
  }
}

PUT my_index/my_type/1
{
  "create_date": "09/25/2015"
}

Numeric detection(数字检测)

虽然JSON支持原生的浮点型和整型数据类型,但是有些应用程序或预言有时会将数字作为字符串。通常正确的解决方案是显式的映射这些字段,但是可以启用数字检测(默认情况下是禁用的)来自动执行此操作。

PUT my_index
{
  "mappings": {
    "my_type": {
      "numeric_detection": true
    }
  }
}

PUT my_index/my_type/1
{
  "my_float":   "1.0",   # 1
  "my_integer": "1"      # 2
}

1

my_float字段已添加为double类型字段。

2

my_integer字段已添加为long类型字段。

Last updated