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 协议》,转载必须注明作者和本文链接