【问题标题】:Partially update a document using scripting and add missing fields使用脚本部分更新文档并添加缺失的字段
【发布时间】:2020-04-27 05:48:11
【问题描述】:

我想知道是否可以使用部分文档更新文档,并使用脚本执行另一个操作,例如,如果我添加 data1,然后添加 data2,我希望我的文档看起来像 final_result。我希望所有内容都被替换和添加,除了标签字段。

data1 = {"name" : "myname", "code" : 123, "tag" : "first"}

data2 = {"name" : "myname", "code" : 555, "tag" : "second", "age":"50", "children": "3"}

final_result = {"name" : "myname", "code" : 555, "tag" : ["first","second"], "age":"50", "children": "3"}

我可以使用此脚本添加标签字段,但我不知道如何同时添加缺少的字段,也不知道可以高级添加哪些字段。

POST myindex/_update/1
{

      "script" : {
        "source": "if(! ctx._source.tag.contains(params.tag)){if (ctx._source.tag instanceof List) { ctx._source.tag.add(params.tag) } else { ctx._source.tag = [ctx._source.tag, params.tag] }}",
        "lang": "painless",
        "params" : {
            "tag" : "sec"
        }
    }

}

如果有人能给我举例说明如何在 python 中做到这一点,我真的很感激。

【问题讨论】:

    标签: python elasticsearch elasticsearch-painless


    【解决方案1】:

    您只需为字段设置新值。

    POST myindex/_update/1
    {
      "script": {
        "source": """
        if(!ctx._source.tag.contains(params.tag)){
            if (ctx._source.tag instanceof List) { 
              ctx._source.tag.add(params.tag) 
    
            } else { 
              ctx._source.tag = [ctx._source.tag, params.tag] 
            }
        }
        ctx._source.code = params.code
            """,
        "lang": "painless",
        "params": {
          "tag": "sec",
          "code": "555"
        }
      }
    }
    

    在 Python 上也是这样,创建 Elasticsearch 实例并调用 update_by_query API

    es = Elasticsearch(['https://user:secret@localhost:443'])
    

    或者……

    es = Elasticsearch(
        ['localhost', 'otherhost'],
        http_auth=('user', 'secret'),
        scheme="https",
        port=443,
    )
    

    然后...正文与您的脚本相同

    self.es.update_by_query(index = indexName, body = q)
    

    【讨论】:

    • 感谢您的回复,我在python中测试并添加了"query": { "match": { "_id": 1 },如果_id不匹配,有没有办法插入文档?
    猜你喜欢
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    • 2012-10-27
    • 1970-01-01
    相关资源
    最近更新 更多