elasticsearch的bulk模式下的curd

前言

学习一下es的bulk api,文档见链接,先写一个简单的demo。

demo

from utils.helpers import get_config_from_file
from internal.libs.esclient import EsClient

# 创建es客户端
global_config = get_config_from_file("../config/config.yaml")
es_client_srv = EsClient(global_config['es'], **global_config['es'].get('addtion', {}))

# 插入2条,修改2条,删除1条
data = [
    {"_op_type": "index", "_index": "test-index", "_id": 1, "_source": {"field1": "value1"}},
    {"_op_type": "index", "_index": "test-index", "_id": 2, "_source": {"field1": "value2"}},
    {"_op_type": "update", "_index": "test-index", "_id": 1, "doc": {"field1": "updated_value1"}},
    {"_op_type": "index", "_index": "test-index", "_id": 2, "_source": {"field1": "updated_value2"}},
    {"_op_type": "delete", "_index": "test-index", "_id": 2}
]
es_client_srv.bulk(data)

# 修改不存在,创建新的
data = [
    {"_op_type": "index", "_index": "test-index", "_id": 2, "_source": {"field1": "updated_value2"}},
]
es_client_srv.bulk(data)

# 修改不存在,报错
data = [
    {"_op_type": "update", "_index": "test-index", "_id": 3, "doc": {"field1": "updated_value2"}},
]
es_client_srv.bulk(data)

# 删除不存在,报错
data = [
    {"_op_type": "delete", "_index": "test-index", "_id": 4}
]
es_client_srv.bulk(data)

总结

bulk模式下,op_type常用的是index、update、delete。update、delete操作在文档不存在时候会报错,index操作在文档不存在时创建新的,类似CreateOrUpdate。op_type还有create操作,用的少就不探讨了。
(注意:update操作,主体内容的key名不是_source而是doc)

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!