Elasticsearch 1.5映射Schema迁移至7.1版本方法咨询
迁移Elasticsearch 1.5映射到7.1版本的解决方案
嘿,刚好帮你梳理下从ES 1.5到7.1的映射迁移问题——核心原因就是ES7.x彻底移除了多文档类型的支持,原来一个索引下挂多个类型(比如users、comment_idea)的写法在7.1里完全行不通了,得按新规则调整。下面给你两种可行方案,优先推荐第一种:
方案一:拆分每个类型为独立索引(推荐,符合ES7+最佳实践)
ES7.1开始要求每个索引只能对应一种文档结构,所以原来的users、comment_idea这些类型,最好各自拆成独立的索引(比如users索引、comment_idea索引)。每个索引的映射需要做两个关键修改:
- 去掉外层的类型名称(比如原来的
"users": {...}层级),直接把properties放在mappings下 - 把过时的
string类型替换成text(用于全文搜索)或keyword(用于精确匹配/聚合)
示例:users索引的新映射
{ "settings": { "index": { "number_of_shards": 1, "number_of_replicas": 0 } }, "mappings": { "properties": { "created_at": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss" }, "id": { "type": "double" }, "name": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "org_id": { "type": "double" }, "type_priority": { "type": "double" } } } }
这里给name字段同时设置了text和keyword子字段:既支持全文搜索,又能做精确匹配或聚合操作,如果你的业务只需要其中一种,也可以只保留text或keyword。
示例:comment_idea索引的新映射
同理,拆成独立索引后,映射结构如下:
{ "settings": { "index": { "number_of_shards": 1, "number_of_replicas": 0 } }, "mappings": { "properties": { "author_id": { "type": "double" }, "comment": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "created_at": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss" }, "id": { "type": "double" }, "idea_id": { "type": "double" }, "org_id": { "type": "double" } } } }
方案二:单索引内用自定义字段区分类型(不推荐,仅特殊场景使用)
如果因为业务限制必须把所有类型放在同一个索引里,可以添加一个自定义字段(比如doc_type)来标记文档所属的原类型,然后把所有字段合并到同一个properties下(注意:如果不同类型有同名字段,必须保证字段类型完全一致,否则会报错)。
示例:合并后的映射
{ "settings": { "index": { "number_of_shards": 1, "number_of_replicas": 0 } }, "mappings": { "properties": { "doc_type": { "type": "keyword" }, // 原users类型的字段 "created_at": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss" }, "id": { "type": "double" }, "name": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "org_id": { "type": "double" }, "type_priority": { "type": "double" }, // 原comment_idea类型的字段 "author_id": { "type": "double" }, "comment": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "idea_id": { "type": "double" } } } }
之后索引文档时,需要给每个文档加上doc_type: "users"或doc_type: "comment_idea",查询时通过doc_type过滤即可。但这种方案会导致索引字段冗余,查询效率也不如拆分索引高,非必要不建议用。
额外注意事项
- ES7.1创建索引时,不能再指定类型名称(比如原来的
PUT /my_index/users这种写法会报错),直接用PUT /users创建索引即可 - 除了
string类型的替换,double、date等类型在7.1里依然兼容,date的格式保留原来的写法也没问题 - 如果你的代码里有按类型查询的逻辑(比如
GET /my_index/users/_search),需要改成对应索引的查询(比如GET /users/_search)
内容的提问来源于stack exchange,提问作者rock3t
相关产品推荐
相关产品推荐

