curl -XPUT 'localhost:9200/my_index/my_type/1?pretty' -H 'Content-Type: application/json' -d' # 1
{
"username": "johnsmith",
"name": {
"first": "John",
"last": "Smith"
}
}
'
curl -XGET 'localhost:9200/my_index/_mapping?pretty' # 2
curl -XPUT 'localhost:9200/my_index/my_type/2?pretty' -H 'Content-Type: application/json' -d' # 3
{
"username": "marywhite",
"email": "[email protected]",
"name": {
"first": "Mary",
"middle": "Alice",
"last": "White"
}
}
'
curl -XGET 'localhost:9200/my_index/_mapping?pretty' # 4
| 1 | 这个文档介绍了字符串字段 username ,对象字段name,和两个在 name 对象下的字符串字段 ,可以称为 name.first 和 name.last。 | | 2 | 检查映射来验证上面的 PUT。 | | 3 | 这个文档添加两个字符串字段 email 和 name.middle。 | | 4 | 检查映射来验证上面的改动. |
新字段如何被检测和添加到映射的细节可以见 Dynamic Mapping.
dynamic 设置控制着新的字段是否可以动态的添加.有三个配置参数:
| true | 新检测的字段被添加到映射中.(默认配置) | | false | 新检测的字段将被忽略。 必须明确添加新字段。 | | strict | 如果检测到新字段,将抛出异常并且文档是拒绝的。 |
dynamic 可以在映射类型级别和每个inner object(内部对象)进行设置。 inner object(内部对象)继承其父对象和来自于映射类型的设置. 例如 :
curl -XPUT 'localhost:9200/my_index?pretty' -H 'Content-Type: application/json' -d'
{
"mappings": {
"my_type": {
"dynamic": false, # 1
"properties": {
"user": { # 2
"properties": {
"name": {
"type": "text"
},
"social_networks": { # 3
"dynamic": true,
"properties": {}
}
}
}
}
}
}
}
'
| 1 | dynamic mapping(动态映射)在类型级别被禁用,所以不会有新的顶级字段动态添加. | | 2 | user 对象继承类型级别设置. | | 3 | user.social_networks 对象允许动态映射,因此可以将新字段添加到该 inner object (内部对象)。 |
建议
dynamic 设置允许在同一索引中相同名称的字段的有不同设置。 可以使用 PUT mapping API(PUT映射API)在现有字段上更新字段的值。