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時,新字段是不能寫入的
