elasticsearch mappings之dynamic的三种状态
elasticsearch mappings之dynamic的三种状态
**本文档操作,均在es7.3进行
一.动态映射(dynamic:true)
1.创建一个索引
PUT commodity?pretty
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 2
},
"mappings": {
"properties": {
"name": {"type": "text"},
"age": {"type": "integer"}
}
}
}
查看mapping信息
{
"commodity" : {
"mappings" : {
"properties" : {
"age" : {
"type" : "integer"
},
"name" : {
"type" : "text"
}
}
}
}
}
添加一条数据,新增字段为sex
PUT commodity/_doc/1
{
"name": "小黑",
"age": 18,
"sex": "不知道"
}
再次查看mapping
{
"commodity" : {
"mappings" : {
"properties" : {
"age" : {
"type" : "integer"
},
"name" : {
"type" : "text"
},
"sex" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
}
}
}
测试查询新字段
GET commodity/_doc/_search
{
"query": {
"match": {
"sex": "不知道"
}
}
}
查询结果
#! Deprecation: [types removal] Specifying types in search requests is deprecated.
{
"took" : 48,
"timed_out" : false,
"_shards" : {
"total" : 3,
"successful" : 3,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.8630463,
"hits" : [
{
"_index" : "commodity",
"_type" : "_doc",
"_id" : "1",
"_score" : 0.8630463,
"_source" : {
"name" : "小黑",
"age" : 18,
"sex" : "不知道"
}
}
]
}
}
此时dymanic默认允许添加新字段
注意: mappings 一旦创建,则无法修改。因为Lucene 生成倒排索引后就不能改了
二.静态映射(dynamic:false)
现在,将dynamic设置为false
PUT commodity2?pretty
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 2
},
"mappings": {
"dynamic": false,
"properties": {
"name": {"type": "text"},
"age": {"type": "integer"}
}
}
}
插入一条数据
PUT commodity2/_doc/1
{
"name": "小黑",
"age": 18,
"sex": "不知道"
}
尝试查询数据,发现此时数据为空,为什么呢?
#! Deprecation: [types removal] Specifying types in search requests is deprecated.
{
"took" : 967,
"timed_out" : false,
"_shards" : {
"total" : 3,
"successful" : 3,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 0,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
}
}
下面,我们来看看commodity2这个索引的mapping
{
"commodity2" : {
"mappings" : {
"dynamic" : "false",
"properties" : {
"age" : {
"type" : "integer"
},
"name" : {
"type" : "text"
}
}
}
}
}
发现了,mapping中,并没有新增sex这个字段,此时的commodity这个索引,只能新增字段,但是并不能通过这个字段查询
总结,新字段,只能写,不能读
严格模式(dynamic:strict)
现在,将dynamic设置为strict模式
PUT commodity3?pretty
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 2
},
"mappings": {
"dynamic": "strict",
"properties": {
"name": {"type": "text"},
"age": {"type": "integer"}
}
}
}
此时,插入数据报错
PUT commodity3/_doc/1
{
"name": "小黑",
"age": 18,
"sex": "不知道"
}
{
"error": {
"root_cause": [
{
"type": "strict_dynamic_mapping_exception",
"reason": "mapping set to strict, dynamic introduction of [sex] within [_doc] is not allowed"
}
],
"type": "strict_dynamic_mapping_exception",
"reason": "mapping set to strict, dynamic introduction of [sex] within [_doc] is not allowed"
},
"status": 400
}
总结,当dynamic设置为strict时,新字段是不能写入的

浙公网安备 33010602011771号