背景
项目中ES写入和部分更新使用JSON表示文档,序列化工具FastJSON将实体中以get开头的方法序列化了,但实际上该字段并不存在。导致Mapping和文档污染,需要重建索引。
文档删除字段
mapping 不能删除字段,只能通过重建。
文档删除字段,通过脚本更新,利用ctx._source.remove(‘fieldName’)删除。
POST waybill_exception_report/_doc/_update_by_query
{
"script": "ctx._source.remove('targetOperationLocation')",
"query": {
"bool": {
"must": [
{
"exists": {
"field": "targetOperationLocation"
}
}
]
}
}
}
也可以利用ctx._source.containsKey(‘fieldName’)来判度文档是都包含指定字段,再进行删除。
POST waybill_exception_report/_doc/_update_by_query
{
"script": "if(ctx._source.containsKey('temperatureLayerColumn')){ctx._source.remove('temperatureLayerColumn')}",
"query": {
"range": {
"beginTime": {
"gte": "2020-05-12"
}
}
}
}
重建索引
Elasticsearch: 权威指南 » 基础入门 » 索引管理 » 重新索引你的数据
Elasticsearch Reference [6.3] » Upgrade Elasticsearch » Reindex before upgrading » Reindex in place
一文搞懂 Elasticsearch 之 Mapping
Mapping
ES 的索引一旦建立,对Mapping的修改只能新增字段,不能对Mapping中已有的字段进行修改、删除。在默认情况下,Mapping的动态映射Dynamic = true,会自动推测字段的类型并添加到Mapping中。
如果是新增加的字段,根据 Dynamic 的设置分为以下三种状况:
- 当 Dynamic 设置为 true 时,一旦有新增字段的文档写入,Mapping 也同时被更新。
- 当 Dynamic 设置为 false 时,索引的 Mapping 是不会被更新的,新增字段的数据无法被索引,也就是无法被搜索,但是信息会出现在 _source 中。
- 当 Dynamic 设置为 strict 时,文档写入会失败。
动态映射参数可以在创建索引时设置,
PUT users
{
"mappings": {
"_doc": {
"dynamic": false
}
}
}
重建索引
对Mapping中已有的字段进行修改时,只能通过重建索引实现:新建一个正确的索引,然后将数据拷贝过去。ES提供reindex来实现重建索引。
使用别名访问索引是不停机重建索引的基础。
步骤:
- 创建一个新的正确索引
- 在新索引上临时关闭自动刷新refresh_interval = -1,设置副本数为number_of_replicas = 0,以加速重建过程。
PUT /my_logs/_settings { "refresh_interval": -1, "number_of_replicas": 0 } - 使用reindex将所有文档从旧索引重新索引到新索引,并记录位置。
如果不仅仅是改变mapping结构,新字段需要由老字段计算而得,则可以使用script参数。POST _reindex?wait_for_completion=false { "source": { "index": "waybill_exception_report" }, "dest": { "index": "waybill_exception_report_v1" }, "script": {...} }
reindex耗时较长,使用wait_for_completion=false使得请求立马返回taskId,使用GET _tasks/{taskID}或者GET _tasks?detailed=true&actions=*reindex可以看到重建进程,其中包含耗时,剩余doc数量等信息。 - 将
refresh_interval和number_of_replicas重置为旧索引中的值,并等待索引状态变成 green。 - 别名变更,该操作为原子操作。
POST /_aliases { "actions" : [ { "remove" : { "index" : "test1", "alias" : "alias1" } }, { "add" : { "index" : "test2", "alias" : "alias1" } } ] } - 同步在重建索引期间旧索引新增的文档
- 删除旧索引
本文介绍了在Elasticsearch中如何删除文档字段及重建索引。由于Mapping不能直接删除字段,需要通过脚本更新或重建索引。重建索引包括创建新索引、关闭自动刷新、使用reindex命令迁移数据、调整别名和同步新文档等步骤,确保过程无损且高效。
1万+

被折叠的 条评论
为什么被折叠?



