在 Elasticsearch 中,映射(mapping)一旦创建,很多结构是不能随意修改的,但“动态更新映射”有几种常见场景和做法。下面按能否改、怎么改、注意事项给你系统讲清楚。
以下字段属性创建后不能修改:
text → keyword、integer → long 等)analyzed / not_analyzed)nested 类型index: false → true如果一定要改这些,只能重建索引(reindex)。
Elasticsearch 默认允许自动添加新字段
PUT /my_index/_doc/1
{
"name": "Tom",
"age": 18
}
如果 age 之前不存在,ES 会自动:
PUT /my_index
{
"mappings": {
"dynamic": "true" // true | false | strict
}
}
| 值 | 行为 |
|---|---|
| true | 自动加字段(默认) |
| false | 忽略新字段 |
| strict | 报错,禁止新字段 |
你可以给已有索引增加新字段
PUT /my_index/_mapping
{
"properties": {
"email": {
"type": "keyword"
}
}
}
✅ 特点:
null适合字段名不规则但类型统一
PUT /my_index
{
"mappings": {
"dynamic_templates": [
{
"strings_as_keyword": {
"match": "*_id",
"mapping": {
"type": "keyword"
}
}
}
]
}
}
效果:
user_id、order_id → 自动变成 keyword部分参数可以改:
PUT /my_index/_mapping
{
"properties": {
"content": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
}
}
}
✅ 可加:
fields(multi-fields)copy_tometa❌ 不能改:
typeanalyzer(已存在数据)PUT /my_index_v2
{
"mappings": {
"properties": {
"age": { "type": "long" }
}
}
}
POST _reindex
{
"source": { "index": "my_index" },
"dest": { "index": "my_index_v2" }
}
# 别名切换
POST _aliases
{
"actions": [
{ "remove": { "index": "my_index", "alias": "my_index_alias" } },
{ "add": { "index": "my_index_v2", "alias": "my_index_alias" } }
]
}
✅ 生产环境:
_mapping 显式添加✅ 调试环境:
dynamic: true| 需求 | 是否可行 |
|---|---|
| 加新字段 | ✅ |
| 改字段类型 | ❌(需 reindex) |
| 改分词器 | ❌ |
| 加 sub-field | ✅ |
| 自动识别字段 | ✅ |
如果你有具体场景(比如“想把 text 改成 keyword”、“ES 7/8 版本”、“日志/电商场景”),可以直接贴出来,我可以给你最合适的方案。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。