es在已有历史数据的文档新增加字段操作

新增字段设置默认值

场景

在已经有大量数据的索引文档上,增加新字段

技术实现

一.更新索引映射

通过PUT请求显式定义新字段类型,确保后续写入的文档能被正确解析

json 复制代码
PUT /文档名/_mapping
{
  "properties": {
    "字段名1": {
      "type": ""
    },
    "字段名2": {
      "type": ""
    }
  }
}
  • 此操作仅定义字段类型,不会自动填充历史文档的默认值

二.设置默认值

1.写入时自动填充(新文档)

通过 Ingest Pipeline 在文档写入前自动添加默认值, 此操作仅对新写入数据生效

bash 复制代码
PUT _ingest/pipeline/set_defaults
{
  "processors": [
    {
      "set": { 
        "field": "like", 
        "value": 0 
      }
    },
    {
      "set": { 
        "field": "disagree", 
        "value": 0 
      }
    }
  ]
}

PUT /文档名/_settings
{
  "index.default_pipeline": "set_defaults"
}

动态判断

bash 复制代码
"script": {
  "source": """
    if (!ctx.containsKey('like')) { ctx.like = 0 }
    if (!ctx.containsKey('disagree')) { ctx.disagree = 0 }
  """
}

2.批量回填历史数据(旧文档)

使用 _update_by_query API 批量更新已有文档

bash 复制代码
POST /service_bot_msg_chat_log/_update_by_query
{
  "script": {
    "source": """
      if (ctx._source.like == null) { ctx._source.like = 0 }
      if (ctx._source.disagree == null) { ctx._source.disagree = 0 }
    """,
    "lang": "painless"
  },
  "query": {
    "bool": {
      "must_not": [
        { "exists": { "field": "like" } },
        { "exists": { "field": "disagree" } }
      ]
    }
  },
  "timeout": "10m",  // 防止超时
  "slices": 5        // 并行分片加速处理
}
  • 性能优化
    • 异步执行:添加 ?wait_for_completion=false 转为后台任务

操作建议

  • 新数据优先:优先配置 Ingest Pipeline,确保增量数据自动初始化
  • 历史数据分治:根据数据量选择 _update_by_query(百万级)或 Reindex(亿级)
相关推荐
屿小夏.7 小时前
【Elasticsearch】Elasticsearch的分片和副本机制
大数据·elasticsearch·jenkins
地瓜伯伯7 小时前
elasticsearch性能调优方法原理与实战
人工智能·elasticsearch·语言模型·数据分析
黑客思维者7 小时前
2025年AI垃圾(AI Slop)现象综合研究报告:规模、影响与治理路径
人工智能·搜索引擎·百度
张彦峰ZYF7 小时前
探索数据的力量:Elasticsearch中指定链表字段的统计查询记录
搜索引擎·性能优化·es
Jinkxs7 小时前
Gradle - 与Elasticsearch集成 构建搜索服务项目
大数据·elasticsearch·搜索引擎
柯南小海盗16 小时前
Elasticsearch同义词配置全攻略
大数据·elasticsearch·jenkins
杰拉拉德16 小时前
Spring AI + Elasticsearch:语义/关键字/混合检索与知识问答
elasticsearch·知识库·rag·spring ai·混合检索·语义检索·关键字检索
yumgpkpm18 小时前
基于GPU的Spark应用加速 Cloudera CDP/华为CMP鲲鹏版+Nvidia英伟达联合解决方案
大数据·数据库·人工智能·hadoop·elasticsearch·spark·cloudera
精致先生19 小时前
ElasticSearch
elasticsearch·搜索引擎
Elastic 中国社区官方博客19 小时前
更高的吞吐量和更低的延迟: Elastic Cloud Serverless 在 AWS 上获得了显著的性能提升
大数据·数据库·elasticsearch·搜索引擎·云原生·serverless·aws