dynamic针对的是新增的字段,不是对mapping中已有的字段 (原有mapping中的字段不受影响,只影响新增的字段)
当dynamic被设置成false的时候,存在新增字段可以被写入到索引文件中,该字段可以被查看到,但是查询不到,同时索引的mapping也为更新显示该新增的字段。
针对整个索引的优先级最高,那么对索引中某个字段设置dynamic为true就不生效了
# 设置索引的mappings,不用事先创建索引
PUT my_index
{
"mappings": {
"dynamic": false,
"properties": {
"user": {
"properties": {
"name": {
"type": "text"
},
"social_networks": {
"dynamic": true,
"properties": {}
}
}
}
}
}
}
# 查看索引的mappings
GET my_index/_mapping
# 手动往索引写入一条数据,写入成功(创建的mapping中有这个字段)
PUT my_index/_doc/1
{
"user.name":"haha"
}
# 可以查看到数据
GET my_index/_doc/1
# 可以查询出来
GET my_index/_search
{
"query": {
"term": {
"user.name": {
"value": "haha"
}
}
}
}
# 手动往索引写入一条数据,写入成功(创建的mapping中没有这个字段)
PUT my_index/_doc/2
{
"age":22
}
# 可以查看到数据
GET my_index/_doc/2
# 查看mapping,还是刚开始创建的,未更新age字段
GET my_index/_mapping
# 查询不出来
GET my_index/_search
{
"query": {
"term": {
"age": {
"value": 22
}
}
}
}
# 索引字段设置dynamic为true的,在这个原有字段下面再新增字段,写入成功
PUT my_index/_doc/3
{
"social_networks.ip":"127.0.0.1"
}
# 查看,可以显示
GET my_index/_doc/3
# 查询不出来
GET my_index/_search
{
"query": {
"term": {
"social_networks.ip": {
"value": "127.0.0.1"
}
}
}
}
# 查看mapping,还是刚开始创建的,未更新social_networks中的ip字段
GET my_index/_mapping
# 往已经存在的文档中更新原先不存在的字段数据,成功
POST my_index/_update/1
{
"doc": {
"social_networks.ip": "127.0.0.1"
}
}
# 可以查看到
GET my_index/_doc/1
# 查询不出来
GET my_index/_search
{
"query": {
"term": {
"social_networks.ip": {
"value": "127.0.0.1"
}
}
}
}
# 给新索引创建mapping,设置dynamic为strict
PUT test
{
"mappings": {
"dynamic": "strict",
"properties": {
"user": {
"type": "text"
}
}
}
}
# 查看mapping
GET test/_mapping
# 新增文档,字段为mapping中已有的字段,成功
PUT test/_doc/1
{
"user":"haha"
}
# 新增文档,字段为mapping中没有的字段,报错400
PUT test/_doc/2
{
"name":"haha"
}
#写入文档,查看 Mapping
PUT mapping_test/_doc/1
{
"firstName":"Chan",
"lastName": "Jackie",
"loginDate":"2018-07-24T10:29:48.103Z"
}
#查看 Mapping文件
GET mapping_test/_mapping
#Delete index
DELETE mapping_test
#dynamic mapping,推断字段的类型
PUT mapping_test/_doc/1
{
"uid" : "123",
"isVip" : false,
"isAdmin": "true",
"age":19,
"heigh":180
}
#查看 Dynamic
GET mapping_test/_mapping
#默认Mapping支持dynamic,写入的文档中加入新的字段
PUT dynamic_mapping_test/_doc/1
{
"newField":"someValue"
}
#该字段可以被搜索,数据也在_source中出现
POST dynamic_mapping_test/_search
{
"query":{
"match":{
"newField":"someValue"
}
}
}
######################### 修改为dynamic false #########################
PUT dynamic_mapping_test/_mapping
{
"dynamic": false
}
#新增 anotherField
PUT dynamic_mapping_test/_doc/10
{
"anotherField":"someValue"
}
#该字段不可以被搜索,因为dynamic已经被设置为false
POST dynamic_mapping_test/_search
{
"query":{
"match":{
"anotherField":"someValue"
}
}
}
get dynamic_mapping_test/_doc/10
#修改为strict
PUT dynamic_mapping_test/_mapping
{
"dynamic": "strict"
}
#写入数据出错,HTTP Code 400
PUT dynamic_mapping_test/_doc/12
{
"lastField":"value"
}
DELETE dynamic_mapping_test