Elastisearch通过查询更新

Ahm*_*lin 6 python elasticsearch

我在python中使用此代码来更新elasticsearch中的文档.它运行正常,但很难将它用于数百万个文档,因为我必须id每次初始化值以更新每个文档.

from elasticsearch import Elasticsearch, exceptions

elasticsearch = Elasticsearch()

elasticsearch.update(index='testindex', doc_type='AAA',   id='AVpwMmhnpIpyZkmdMQkT',
                 body={
                     'doc':{'Device': 'updated'}
                 }
                 )
Run Code Online (Sandbox Code Playgroud)

我在Elasticsearch文档中读到它尚未包含但是:https: //www.elastic.co/guide/en/elasticsearch/reference/current/_updating_documents.html

请注意,在撰写本文时,一次只能对单个文档执行更新.将来,Elasticsearch可以提供在给定查询条件(如SQL UPDATE-WHERE语句)的情况下更新多个文档的功能.

chr*_*abo 13

使用update_by_query(而不是update)和script,您应该能够更新与您的查询匹配的文档.

 q = {
     "script": {
        "inline": "ctx._source.Device='Test'",
        "lang": "painless"
     },
     "query": {
        "match": {
            "Device": "Boiler"
        }
     }
}

es.update_by_query(body=q, doc_type='AAA', index='testindex')
Run Code Online (Sandbox Code Playgroud)

以上对我有用.在q找到符合您查询的文件和脚本更新使用值_source的每个文件.

我希望它也适合你,可能会对你想要使用的查询进行一些调整.

  • @Kourosh,您需要传递冲突值,以避免错误。es.update_by_query(body=q, doc_type='AAA', index='testindex',conflicts='proceed') 这将忽略冲突错误。 (2认同)