一、Array裡邊的元素是String
# 建立一條資料
POST test_index/test_type/1
{
"tags":["tag1", "tag2", "tag3"]
}
# 檢視資料
GET test_index/test_type/1
# 給 _id=1 的tags增加一個 tag5
POST test_index/test_type/1/_update
{
"script" : {
"source": "ctx._source.tags.add(params.tag)",
"params" : {
"tag" : "tag5"
}
}
}
# _id=1 的tags移除 tag5
POST test_index/test_type/1/_update
{
"script" : {
"source": "ctx._source.tags.remove(ctx._source.tags.indexOf(params.tag))",
"params" : {
"tag" : "tag5"
}
}
}
# 查詢 tag1 in tags 移除tag2
POST test_index/test_type/_update_by_query
{
"query": {
"term": {
"tags": "tag1"
}
},
"script": {
"source": "ctx._source.tags.remove(ctx._source.tags.indexOf(params.tag))",
"params": {
"tag": "tag2"
}
}
}
二、Array裡邊包含對象
# 添加一條資料
POST /blog-test/doc/AXiHn9l3CFuw25Pb9kYM
{
"title": "Invest Money",
"body": "Please start investing money as soon...",
"tags": [
"money",
"invest"
],
"published_on": "18 Oct 2017",
"comments": [
{
"name": "William",
"age": 34,
"rating": 8,
"comment": "Nice article..",
"commented_on": "30 Nov 2017"
},
{
"name": "John",
"age": 38,
"rating": 9,
"comment": "I started investing after reading this.",
"commented_on": "25 Nov 2017"
},
{
"name": "Smith",
"age": 33,
"rating": 7,
"comment": "Very good post",
"commented_on": "20 Nov 2017"
}
]
}
# 數組添加一條資料
POST /blog-test/doc/AXiHn9l3CFuw25Pb9kYM/_update
{
"script": {
"source": "ctx._source.comments.add(params.new_comment)",
"params": {
"new_comment": {
"name": "xiang",
"age": 25,
"rating": 18,
"comment": "very very good article...",
"commented_on": "3 Nov 2018"
}
}
}
}
# 數組移除一條資料
POST /blog-test/doc/AXiHn9l3CFuw25Pb9kYM/_update
{
"script": {
"lang": "painless",
"source": "ctx._source.comments.removeIf(it -> it.name == 'John');"
}
}
# 數組更新一條資料
POST /blog-test/doc/AXiHn9l3CFuw25Pb9kYM/_update
{
"script": {
"source": "for(e in ctx._source.comments){if (e.name == 'Smith') {e.age = 25; e.comment= 'very very good article...';}}"
}
}
參考
Elasticsearch局部更新(數組追加) Elasticsearch 5.6.3 通過script添加、删除數組元素