实现往 _id 为 0000000000 的 doc 中的 field_1 字段中带去重的追加数组元素 “111”,逻辑如下:
如果 (没有 _id 为 0000000000的 doc) {
利用 upsert 创建该 doc
} 否则 {
如果 (该 doc 中包含 field_1 字段) {
如果 (field_1 字段的值中不包含 "111") {
在 field_1 字段中添加 "111"
}
} 否则 {
创建 field_1 字段,并将 "111"写入
}
}
在 kibana 下的代码:
POST test_index/test_type/0000000000/_update
{
"script" : {
"source": "if(ctx._source.containsKey('field_1')){if(!ctx._source.field_1.contains('111')){ctx._source.field_1.add('111')}}else{ctx._source.field_1=['111']}"
},
"upsert": {
"field_0":"0000000000",
"field_1":["111"]
}
}
在 curl 下执行一条语句的代码:
curl -XPOST http://192.168.1.100:9200/test_index/test_type/0000000000/_update -H 'Content-Type: application/json' -d '{"script":{"source":"if(ctx._source.containsKey('field_1')){if(!ctx._source.field_1.contains('111')){ctx._source.field_1.add('111')}}else{ctx._source.field_1=['111']}"},"upsert":{"field_0":"0000000000","field_1":["111"]}}'
在 curl 下执行一个文件的代码(-H ‘Content-Type: application/json’ 为 6.x 之后需要):
curl -XPOST http://192.168.1.100:9200/test_index/test_type/_bulk -H 'Content-Type: application/json' --data-binary @yourpath/yourfile
其中文件每两行的内容:
{"update":{"_id":"0000000000"}}
{"script":{"source":"if(ctx._source.containsKey('field_1')){if(!ctx._source.field_1.contains('111')){ctx._source.field_1.add('111')}}else{ctx._source.field_1=['111']}"},"upsert":{"field_0":"0000000000","field_1":["111"]}}
另外,script 中的变量可以用参数(params)表示,以在 kibana 下的代码为例:
POST test_index/test_type/0000000000/_update
{
"script" : {
"source": "if(ctx._source.containsKey(params.fieldname)){if(!ctx._source.field_1.contains(params.content)){ctx._source.field_1.add(params.content)}}else{ctx._source.field_1=[params.content]}",
"params": {
"fieldname": "field_1",
"content": "111"
}
},
"upsert": {
"field_0":"0000000000",
"field_1":["111"]
}
}