【问题标题】:Elastisearch update by queryElasticsearch 通过查询更新
【发布时间】:2017-07-18 06:40:42
【问题描述】:

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

from elasticsearch import Elasticsearch, exceptions

elasticsearch = Elasticsearch()

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

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

请注意,在撰写本文时,更新只能在 一次单个文档。未来,Elasticsearch 可能会提供 给定查询条件更新多个文档的能力(例如 SQL UPDATE-WHERE 语句)。

【问题讨论】:

  • 我很确定 update_by_query 作为参数 q 应该可以工作。只需检查一下 python elasticsearch-py.readthedocs.io/en/master/…
  • 您好 AhmyOhlin,欢迎来到该网站。我编辑了您的问题以匹配本网站上其他问题的格式,请随时再次编辑。
  • @christinabo 我想将设备的值从“锅炉”更改为“测试”。我使用参数 q ='Device:"Boiler"' 来更新所有值为 'boiler' 的文档,但出现以下错误:TypeError: update() got an unexpected keyword argument 'q' 这是我的代码 elasticsearch.update(index='testindex', doc_type='AAA', q ='Device:"Boiler"', body={ 'doc':{'Device': 'TESTs'} }
  • @Blairg23:我的问题是搜索所有包含Device:"Boiler"' 的文档然后更新它我的问题是:我如何在更新帮助操作中使用 q 参数 python 说:q – Lucene 查询中的查询字符串语法我不明白我是如何使用它的,因为没有例子。

标签: python elasticsearch


【解决方案1】:

使用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')

以上对我有用。 q 查找与您的查询匹配的文档,脚本使用每个文档的 _source 更新值。

我希望它也适用于您,可能需要对您要使用的查询进行一些调整。

【讨论】:

  • 我试过你的代码,它工作正常。感谢您的帮助。
  • 有没有办法将其作为 upsert 执行?
  • 我使用您的示例代码收到此错误:elasticsearch.exceptions.ConflictError: ConflictError(409)
  • @Kourosh 您需要传递冲突值,以避免错误。 es.update_by_query(body=q, doc_type='AAA', index='testindex', conflict='proceed') 这将忽略冲突错误。
猜你喜欢
  • 2017-01-02
  • 1970-01-01
  • 2017-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多