新增字段設置默認值
場景
在已經有大量數據的索引文檔上,增加新字段
技術實現
一.更新索引映射
通過PUT請求顯式定義新字段類型,確保后續寫入的文檔能被正確解析
PUT /文檔名/_mapping
{"properties": {"字段名1": {"type": ""},"字段名2": {"type": ""}}
}
- 此操作僅定義字段類型,不會自動填充歷史文檔的默認值
二.設置默認值
1.寫入時自動填充(新文檔)
通過 Ingest Pipeline 在文檔寫入前自動添加默認值, 此操作僅對新寫入數據生效
PUT _ingest/pipeline/set_defaults
{"processors": [{"set": { "field": "like", "value": 0 }},{"set": { "field": "disagree", "value": 0 }}]
}PUT /文檔名/_settings
{"index.default_pipeline": "set_defaults"
}
動態判斷
"script": {"source": """if (!ctx.containsKey('like')) { ctx.like = 0 }if (!ctx.containsKey('disagree')) { ctx.disagree = 0 }"""
}
2.批量回填歷史數據(舊文檔)
使用 _update_by_query
API 批量更新已有文檔
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
(億級)