Elasticsearch partial update script: Clear array and replace with new values

后端 未结 2 647
囚心锁ツ
囚心锁ツ 2021-01-13 03:20

I have documents like:

{
  MyProp: [\"lorem\", \"ipsum\", \"dolor\"]
  ... lots of stuff here ...
}

My documents can be quite big (but thes

相关标签:
2条回答
  • 2021-01-13 03:59

    You can use the update by query API in order to do batch updates. This works since ES 2.3 onwards, otherwise you need to install a plugin.

    POST index/_update_by_query
    {
      "script": {
        "inline": "ctx._source.myProp += newProp",
        "params": {
          "newProp": "sit"
        }
      },
      "query": {
        "match_all": {}
      }
    }
    

    You can of course use whatever query you want in order to select the documents on which MyProp needs to be updated. For instance, you could have a query to select documents having some specific MyProp values to be replaced.

    The above will only add a new value to the existing array. If you need to completely replace the MyProp array, then you can also change the script to this:

    POST index/_update_by_query
    {
      "script": {
        "inline": "ctx._source.myProp = newProps",
        "params": {
          "newProps": ["dolor", "sit"]
        }
      },
      "query": {
        "match_all": {}
      }
    }
    

    Note that you also need to enable dynamic scripting in order for this to work.

    UPDATE

    If you simply want to update a single document you can use the partial document update API, like this:

    POST test/type1/1/_update
    {
        "doc" : {
            "MyProp" : ["dolor", "sit"]
        }
    }
    

    This will effectively replace the MyProp array in the specified document.

    If you want to go the bulk route, you don't need scripting to achieve what you want:

    POST index/type/_bulk
    { "update" : {"_id" : "1"} }
    { "doc" : {"MyProp" : ["dolor", "sit"] } }
    { "update" : {"_id" : "2"} }
    { "doc" : {"MyProp" : ["dolor", "sit"] } }
    
    0 讨论(0)
  • 2021-01-13 04:09

    Would a _bulk update work for you?

    POST test/type1/_bulk
    {"update":{"_id":1}}
    {"script":{"inline":"ctx._source.MyProp += new_param","params":{"new_param":"bla"},"lang":"groovy"}}
    {"update":{"_id":2}}
    {"script":{"inline":"ctx._source.MyProp += new_param","params":{"new_param":"bla"},"lang":"groovy"}}
    {"update":{"_id":3}}
    {"script":{"inline":"ctx._source.MyProp += new_param","params":{"new_param":"bla"},"lang":"groovy"}}
    ....
    

    And you would also need to enable inline scripting for groovy. What the above would do is to add a bla value to the listed documents in MyProp field. Of course, depending on your requirements many other changes can be performed in that script.

    0 讨论(0)
提交回复
热议问题