使用Python编写批量更新Elasticsearch数据的脚本需要使用elasticsearch库和json库。以下是一个示例代码:
from elasticsearch import Elasticsearch,helpers
import json
#连接Elasticsearch
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
bulk_data = []
# 添加要批量更新的文档
bulk_data.append({
"update": {"_index": "my_index", "_id": "1"}
})
bulk_data.append({
"doc": {
"name": "John Doe",
"age": 25,
"email": "johndoe@email.com"
}
})
bulk_data.append({
"update": {"_index": "my_index", "_id": "2"}
})
bulk_data.append({
"doc": {
"name": "Jane Smith",
"age": 30,
"email": "janesmith@email.com"
}
})
#用helpers.bulk处理批量更新请求
result = helpers.bulk(es, bulk_data)
#输出结果
print(json.dumps(result, indent=2))
以上脚本将更新Elasticsearch的 "my_index" 索引中具有ID 1和2的文档。要添加更多文档,只需添加更多的 "bulk_data.append" 行即可。