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

后端 未结 2 648
囚心锁ツ
囚心锁ツ 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"] } }
    

提交回复
热议问题