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数组
- Elasticsearchrch 教程中,是这样实现的
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"
]
}
}
成功添加
本文介绍了如何在Elasticsearch 5.4.0版本中进行局部更新,特别是针对数组字段的追加操作。通过创建新文档和使用脚本,将新标签“tag4”添加到已有的tags数组中,如“tag1”、“tag2”和“tag3”。在更新过程中遇到了错误,但通过查找资料找到了正确的解决方案。
&spm=1001.2101.3001.5002&articleId=79401138&d=1&t=3&u=a9d2618ff59649c3a5cadedfd024f066)
2608

被折叠的 条评论
为什么被折叠?



