24.基于groovy脚本进行partial update

主要知识点

   

es中其实是有内置的脚本支持的,可以基于groovy脚本实现各种各样的复杂操作

基于groovy脚本,如何执行partial update

es scripting module,我们会在高手进阶篇去讲解,这里就只是初步讲解一下

一、先准备数据

PUT /test_index/test_type/11

{

"num": 0,

"tags": []

}

   

二、使用内置脚本对数据进行更新

POST /test_index/test_type/11/_update

{

"script" : "ctx._source.num+=1"

}

结果如下:可以看到,此时num的值从0变为1

{

"_index": "test_index",

"_type": "test_type",

"_id": "11",

"_version": 2,

"found": true,

"_source": {

"num": 1,

"tags": []

}

}

   

三、使用外部脚本对数据进行更新

1、先在es安装目录下的script目录下新建一个脚本文件,文件名为test-add-tags.groovy

2、在test-add-tags.groovy文件中写入 ctx._source.tags+=new_tag,然后保存退出

3、在kibana中执行以下语句:

   

POST /test_index/test_type/11/_update

{

"script": {

"lang": "groovy",

"file": "test-add-tags",

"params": {

"new_tag": "tag1"

}

}

}

结果如下:可以看到,tags这个数组中已加入一个数据。

   

四、使用用脚本删除文档

1、先在es安装目录下的script目录下新建一个脚本文件,文件名为test-delete-document.groovy

2、在test-delete-document.groovy文件中写入

ctx.op = ctx._source.num == count ? 'delete' : 'none'

然后保存退出

3、在kibana中执行以下语句:

   

POST /test_index/test_type/11/_update

{

"script": {

"lang": "groovy",

"file": "test-delete-document",

"params": {

"count": 1

}

}

}

执行结果如下,因为执行前num的值为1,所以符合条件,把该文档删除

执行 GET /test_index/text_type/11 结果如下:可以看到,此时是把整个文档都删除,整个文档都不存在了

   

   

五、upsert操作

1、先执行以下语句(在没有该文档的情况下进行更新)

   

POST /test_index/test_type/11/_update

{

"doc": {

"num": 1

}

}

结果如下:

说明,如果不存在该文档是不能执行更新操作的,使用upsert进行操作的话,如果指定的document不存在,就执行upsert中的初始化操作;如果指定的document存在,就执行doc或者script指定的partial update操作

   

2、在kibana中执行以下语句:

   

POST /test_index/test_type/11/_update

{

"script" : "ctx._source.num+=1",

"upsert": {

"num": 0,

"tags": []

}

}

结果如下:此时插入numtags的值(初始化)

再执行一次上述语句,结果如下,此时把num1

   

posted @ 2018-02-23 21:04  outback123  阅读(199)  评论(0编辑  收藏  举报