ES由内置的脚本支持,可以基于groovy脚本实现各种各样的复杂操作。
数据准备
| PUT /test_index/test_type/1 { “num”: 0, “tags”:[] } |
|---|
1、内置脚本
| POST /test_index/test_type/1/_update { “script”: “ctx._source.num+=1” } |
|---|
2、外部脚本
文件位置:es安装路径/config/scripts/test-add-tags.goovery
文件内容:
| ctx._source.tags+=new_tag |
|---|
执行脚本
| POST /test_index/test_type/1/_update { “script”: { “lang”: “groovy”, “file”: “test-add-tags”, “params”: { “new_tag”:”tag1” } } } |
|---|
3、用脚本删除文档
| ctx.op=ctx._source.num==count?’delete’:’none’ |
|---|
执行
| POST /test_index/test_type/1/_update { “script”: { “lang”: “groovy”, “file”: “test-delete-document”, “params”: { “count”:”1” } } } |
|---|
4、upsert操作
如果某一个文档已经deleted,再对这个文档进行更新,会报错error
使用upsert语句,如果指定的document不存在,就执行upsert中的初始化操作;如果指定的documen存在,就执行doc或者script中指定的partial update操作
| POST /test_index/test_type/1/_update { “script”: “ctx._source.num+=1”, “upsert”: { “num”:1, “tags”:[] } } |
|---|
