Elasticsearch新增和删除索引中的字段

在ES中,增加字段相对比较容易,因为ES支持动态映射(Dynamic Mapping)。

当索引中新增文档时,ES可以根据文档中的字段自动创建对应的映射关系。如果新字段类型与已有字段类型不同,ES会自动将已有字段类型转换为新类型。

而删除字段则比较困难,因为ES的索引是基于倒排索引的。

当一个字段被索引后,它就会被写入到倒排索引中。

如果删除该字段,就需要删除所有文档中该字段对应的倒排索引,这个过程非常耗时和复杂。

另外,如果删除了一个字段,可能会影响已有的查询和聚合操作,因为这些操作可能依赖于该字段。

因此,在ES中删除字段不是一个常见的操作,通常需要通过创建新的索引来实现。

可以通过创建新的索引并将数据导入新索引的方式来实现增删字段的需求。

虽然这种方式需要重新建立索引,但可以保证数据的完整性和一致性。

简单说,ES实现字段删除的步骤,就是把原索引中除要删除的索引字段外的所有属性,复制到一个新索引上,然后删除就索引,再重建旧索引(没有要删除的字段),然后再把新索引的所有属性,复制到新建的旧索引上。

1、新建索引my_temp_index

2、索引my_temp_index插入一条数据

3、索引my_temp_index查询数据

4、假设要删除的字段是picture_url,先把这个字段的内容删除

注意:

只是删除数据,不是删除字段

如果不删除字段数据,后面reindex时依然会把待删除字段的值带到新索引,即使设置新索引的dynamic为false

4、新建索引my_temp_index_new,不包含picture_url字段

5、同步数据,将my_temp_index旧索引的数据,同步到新索引my_temp_index_new中。注意,这个同步操作前,一定要确保旧索引my_temp_index的picture_url属性是没有值的。否则,这个同步过程,会把picture_url字段带到新索引上

6、验证效果,查询新索引my_temp_index_new映射关系与新索引数据

7、删除原索引

8、新建一个名为原索引名的索引my_temp_index,reindex同步数据,然后删除步骤4新建的索引my_temp_index_new

以上步骤,涉及到的命令如下:

复制代码
get /my_temp_index/_mapping

get /my_temp_index_new/_mapping


DELETE /my_temp_index
DELETE /my_temp_index_new

PUT /my_temp_index
{
	"settings": {
		"number_of_shards": 5,
		"number_of_replicas": 1
	},
	"mappings": {
		"_doc": {
			"properties": {
				"commodity_id": {
					"type": "long"
				},
				"commodity_name": {
					"type": "text"
				},
				"picture_url": {
					"type": "keyword"
				},
				"price": {
					"type": "double"
				}
			}
		}
	}
}

PUT /my_temp_index_new
{
	"settings": {
		"number_of_shards": 5,
		"number_of_replicas": 1
	},
	"mappings": {
		"_doc": {
			"properties": {
				"commodity_id": {
					"type": "long"
				},
				"commodity_name": {
					"type": "text"
				},
				"price": {
					"type": "double"
				}
			}
		}
	}
}

POST /_reindex
{
    "source": {
        "index": "my_temp_index"
    },
    "dest": {
        "index": "my_temp_index_new"
    }
}

GET my_temp_index/_search
{
  "query": {
    "match_all": {}
  }
}

GET my_temp_index_new/_search
{
  "query": {
    "match_all": {}
  }
}


get my_temp_index/_mapping

post /my_temp_index/_doc
{
  "commodity_id":1,
  "commodity_name":"xxx1",
  "picture_url":"actress",
  "price": 999.00
}


POST  /my_temp_index/_update_by_query
{
    "script": {
        "lang": "painless",
        "inline": "ctx._source.remove(\"picture_url\")"
    },
    "query": {
        "match_all": {}
    }
}

参考【es】Elasticsearch新增和删除索引中的字段 - 简书

相关推荐
极限实验室16 分钟前
搜索百科(1):Lucene —— 打开现代搜索世界的第一扇门
搜索引擎·lucene
阿里云大数据AI技术7 小时前
StarRocks 助力数禾科技构建实时数仓:从数据孤岛到智能决策
大数据
Lx35211 小时前
Hadoop数据处理优化:减少Shuffle阶段的性能损耗
大数据·hadoop
Elasticsearch14 小时前
平衡尺度:利用权重使倒数排序融合 (RRF) 更加智能
elasticsearch
武子康15 小时前
大数据-99 Spark Streaming 数据源全面总结:原理、应用 文件流、Socket、RDD队列流
大数据·后端·spark
阿里云大数据AI技术1 天前
大数据公有云市场第一,阿里云占比47%!
大数据
Lx3521 天前
Hadoop容错机制深度解析:保障作业稳定运行
大数据·hadoop
muyun28002 天前
Docker 下部署 Elasticsearch 8 并集成 Kibana 和 IK 分词器
elasticsearch·docker·容器
T06205142 天前
工具变量-5G试点城市DID数据(2014-2025年
大数据
向往鹰的翱翔2 天前
BKY莱德因:5大黑科技逆转时光
大数据·人工智能·科技·生活·健康医疗