ES单条数据录入操作

  • 录入数据时先在库里进行查询,如果数据存在的话,进行更新数据;如果库里面此条数据不存在的话,进行插入数据
  • 以下是封装的完整代码可以参考
from elasticsearch import Elasticsearch

url = 'http://%s:%s/' % ('ip', 'port')
ES = Elasticsearch(url)

query = {
        "query": {
            "bool": {
                "must": [],
            }
        }
}

def search_from_es(query, index, doc_type='type'):
    """ 根据查询条件在ES中查找是否有对应的数据 """

    update_id = None
    search_result = False
    exception = False
    try:
        res = ES.search(body=query, index=index, doc_type=doc_type)
    except Exception as e:
        exception = True
    else:
        if res["hits"]["total"] > 0:
            hits = res["hits"]["hits"][0]
            update_id = hits["_id"]
            search_result = True

    return search_result, update_id, exception

def load_data():
    doc = {'values':['1.1.1.1']}               # 需要进行操作的那条数据
    index = 'index'        # 索引名或者索引别名
    ip = doc['values'][0]  # 可以识别数据唯一性的字段
    temp = {"term": {"values": ip}}
    query["query"]["bool"]["must"].append(temp)

    search_result, update_id, exception = search_from_es(query, index)
    if search_result:
        # 执行数据更新操作
        try:
            ES.update(index=index, doc_type='type', id=update_id, body={"doc": doc})
        except Exception as e:
            print(e)
            message = "Internal server error"
            code = 500
            status = 500
    elif exception:
        # 查询数据出现异常
        message = "Internal server error"
        code = 500
        status = 500
    else:
        # 执行数据插入操作
        try:
            ES.index(index=index, doc_type='type', id=update_id, body=doc)
        except Exception as e:
            print(e)
            message = "Internal server error: index"
            code = 500
            status = 500
    

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值