Elasticsearch局部更新(数组追加)

本文介绍了如何在Elasticsearch 5.4.0版本中进行局部更新,特别是针对数组字段的追加操作。通过创建新文档和使用脚本,将新标签“tag4”添加到已有的tags数组中,如“tag1”、“tag2”和“tag3”。在更新过程中遇到了错误,但通过查找资料找到了正确的解决方案。

Elasticsearch局部更新(数组追加)

现在需要实现这样一个功能:(本人使用ES版本为5.4.0)
比如:我这需要操作的某个字段tags:[“tag1”,”tag2”,”tag3’] , 现在发现了一个新标签”tag4”,需要加入到tags中。

第1步:创建一个新文档 - 确定(index = test_index; type = test_type; id = 1)

POST test_index/test_type/1
{
  "tags":["tag1", "tag2", "tag3"]  
}

第2步:使用脚本将附加值附加到tags数组

POST test_index/test_type/1/_update
{
   "script" : "ctx._source.tags+=new_tag",
   "params" : {
      "new_tag" : "tag4"
   }
}

然后出现这个错误

{
  "error": {
    "root_cause": [
      {
        "type": "remote_transport_exception",
        "reason": "[**_test_01][**.**.**.**:9300][indices:data/write/update[s]]"
      }
    ],
    "type": "illegal_argument_exception",
    "reason": "failed to execute script",
    "caused_by": {
      "type": "script_exception",
      "reason": "compile error",
      "script_stack": [
        "ctx._source.tags+=new_tag",
        "                  ^---- HERE"
      ],
      "script": "ctx._source.tags+=new_tag",
      "lang": "painless",
      "caused_by": {
        "type": "illegal_argument_exception",
        "reason": "Variable [new_tag] is not defined."
      }
    }
  },
  "status": 400
}
  • 经过我上网找了一些资料后,应该是这样写:
POST test_index/test_type/1/_update
{
   "script" : {
       "inline": "ctx._source.tags.add(params.new_tag)",
       "params" : {
          "new_tag" : "tag4"
       }
   }
}

查看一下:

{
  "_index": "test_index",
  "_type": "test_type",
  "_id": "1",
  "_version": 32,
  "found": true,
  "_source": {
    "tags": [
      "tag1",
      "tag2",
      "tag3",
      "tag4"
    ]
  }
}

成功添加

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值