elasticsearch指定字段批量更新

创建index时候将想要更新的字段默认值为None,更新字段时候一定要指定我们创建index的id,且source部分要将我们要更新的字段==null,因为None在es中为null

from elasticsearch6 import Elasticsearch
from elasticsearch6.helpers import bulk, scan
es = Elasticsearch(hosts='127.0.0.1', port=9200)

def create_index():
    actions = []
    clicks_times = None
    commented_times = None
    action = {
        "_index": 'qwer',
        "_type": 'qwer',
        "_source": {
            "clicks_times": clicks_times,
            "commented_times": commented_times,
        }
    }
    actions.append(action)
    success, _ = bulk(es, actions, index='qwer', raise_on_error=True)



def update_index():
    replies = 2
    views = 3
    insert_body = {
        "script": {
            "source": "if (ctx._source.clicks_times==null) {ctx._source.clicks_times=params.clicks_times} if (ctx._source.commented_times==null) {ctx._source.commented_times=params.commented_times}",
            "params": {
                "clicks_times": int(replies),
                "commented_times": int(views)
            }
        }
    }
    es.update(index="qwer", doc_type="qwer", id='AXD11MoArN4EYUumnvGX', body=insert_body)


if __name__ == '__main__':
    create_index()
    update_index()

你可能感兴趣的:(Elasticsearch)