18. ElasticSearch系列之批量插入与更新
本文介绍工作中Python版常用的高效ES批量插入、更新数据方式
1. 批量插入
import pandas as pd
from elasticsearch import helpers
actions = list()
count = 0
for index, item in merged_df.iterrows():
// 过滤nan值
filted_item = dict(filter(lambda x: pd.notna(x[1]),item.items()))
action = {
"_op_type": "index", // index update
"_index": "community_summary", // 索引名
"_id": item['id'], // 文档ID
"_source": filted_item // 文档值
}
actions.append(action)
if len(actions) == 1000:
// 批量写入
helpers.bulk(es12_client.elastic_client, actions)
count += len(actions)
print(count)
actions.clear()
if len(actions) > 0:
helpers.bulk(es12_client.elastic_client, actions)
count += len(actions)
print(count)
actions.clear()
2.批量更新
批量更新只需要改动action的以下内容即可
action = {
'_op_type': 'update', // 此处改为update
'_index': item['index'],
'_id': item_['_id'],
'doc': {'estate_type': item['映射物业类型']} // key值改为doc即可
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~