当 Elasticsearch 遇到文档中以前 未遇到的字段,它用 dynamic mapping(动态映射) 来确定字段的数据类型并自动把新的字段添加到类型映射。
有时这是想要的行为有时又不希望这样。通常没有人知道以后会有什么新字段加到文档,但是又希望这些字段被自动的索引。也许你只想忽略它们。如果Elasticsearch是作为重要的数据存储,可能就会期望遇到新字段就会抛出异常,这样能及时发现问题。
dynamic
- true:遇到陌生字段就 dynamic mapping
- false:遇到陌生字段就忽略
- strict:遇到陌生字段就报错
# 设置为报错
PUT /lib8
{
"settings":{
"number_of_shards": 3,
"number_of_replicas": 0
},
"mappings":{
"user":{
"dynamic": strict,
"properties": {
"name": {"type": "text"},
"address": {"type": "object", "dynamic": true}
}
}
}
}
# 插入以下文档,将会报错
# user此层设置dynamic是strict,在user层内设置age将报错
# 在address层设置dynamic是ture,将动态映射生成字段
PUT /lib8/user/1
{
"name": "lisi",
"age": "20",
"address": {
"province": "beijing",
"city": "beijing"
}
}
date_detection:
默认值是true,会按照一定格式识别date,比如yyyy-MM-dd
# 可以手动关闭某个type的date_detection
PUT /lib8
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 0
},
"mappings": {
"user": {
"date_detection": false
}
}
}
# 定制 dynamic mapping template(type)
# match: *_en 表示是字段名是以_en结尾
# match_mapping_type: string 表示是添加的所有string类型的字段都用这个模板
# mapping.type: text 表示是字段的值是text类型
# mapping.analyzer: english 表示是分词是english分词器
PUT /my_index
{
"mappings": {
"my_type": {
"dynamic_templates": [
{
"en": {
"match": "*_en",
"match_mapping_type": "string",
"mapping": {
"type": "text",
"analyzer": "english"
}
}
}
]
}
}
}
# 使用模板
PUT /my_index/my_type/3
{
"title_en": "this is my dog"
}
# 未使用模板,使用standard分词器
PUT /my_index/my_type/5
{
"title": "this is my cat"
}
# 查询title_en,将无法查出数据(english分词)
# 查询title,将查出数据(standard分词)
GET /my_index/my_type/_search
{
"query": {
"match": {
"title": "is"
}
}
}