当Es索引因需求需要添加字段时,有三种方案
通过删除旧索引,新建新索引来解决,但是这种方案需要全量跑数据,且平台会出现短暂不可用,不建议使用 新创建一个临时索引,然后把旧索引数据导入后,再把新索引别名命名为旧索引,但这种方式,索引别名让虽然不影响使用,但是很难受 直接通过命令来实现 修改es索引,推荐使用kibana操作
第一步:查询索引结构
GET news/_mapping 1 第二步:查看索引是否允许被修改
GET news/_settings 1 结果:
{ "news": { "settings": { "index": { "number_of_shards": "5", "blocks": { "read_only_allow_delete": "true" }, "provided_name": "news", "creation_date": "1605592385832", "number_of_replicas": "1", "uuid": "mbjw8PTFR9qS5VWW7qqjXQ", "version": { "created": "6030299" } } } } }
查看结果中的 read_only_allow_delete是否为true,为true时即可修改,如果为false时,说明索引时只读状态,添加时会出现如下错误:
{ "error": { "root_cause": [ { "type": "cluster_block_exception", "reason": "index [blog1] blocked by: [FORBIDDEN/12/index read-only / allow delete (api)];" } ], "type": "cluster_block_exception", "reason": "index [blog1] blocked by: [FORBIDDEN/12/index read-only / allow delete (api)];" }, "status": 403 }
需要我们执行以下命令:
PUT news/_settings { "index.blocks.read_only_allow_delete": null }
第三步:添加新字段
GET news/_mapping/main { "main": { "properties":{ "isExhibition": { "type": "integer" }, "groupNo": { "type": "keyword" }, "groupName": { "type": "keyword" } } } }
注意,news为索引名,main为索引体,需要和GET查询出来的结果对应上,否则会报错
{ "error": { "root_cause": [ { "type": "illegal_argument_exception", "reason": "Rejecting mapping update to [news] as the final mapping would have more than 1 type: [main, type]" } ], "type": "illegal_argument_exception", "reason": "Rejecting mapping update to [news] as the final mapping would have more than 1 type: [main, type]" }, "status": 400