Elasticsearch 基于groovy脚本实现partial update

partial update

首先,了解下,什么是partial update,与传统的update有什么区别?

传统的update,一般的实现方式,先发起一个get请求,获取到document,然后再做修改,发送put请求PUT /index/type/id,到es中,进行全量替换。es将老的document标记为deleted,然后重新创建一个新的document。

而partial update,语法如下

post /index/type/id/_update 
{
   "doc": {
      "要修改的少数几个field即可,不需要全量的数据"
   }
}

每次就传递少数几个发生修改的field即可,不需要将全量的document数据发送过去
加上partial update,实际上不需要一开始从es重请求document,所以会节省很多的时间和减少并发锁的冲突问题。

groovy脚本

es,其实是有个内置的脚本支持的,可以基于groovy脚本实现各种各样的复杂操作;这一此,只是单纯的讲下基于groovy脚本,如何执行partial update。
而具体的scripting module,以后再好好学习。

## 新建一个索引
PUT /test_index/test_type/11
{
  "num": 0,
  "tags": []
}

1.内置脚本

POST /test_index/test_type/11/_update
{
   "script" : "ctx._source.num+=1"
}
## 返回
{
  "_index": "test_index",
  "_type": "test_type",
  "_id": "11",
  "_version": 2,
  "found": true,
  "_source": {
    "num": 1,
    "tags": []
  }
}

2.外部脚本

首先,在你的es的安装目录下,新建一个groovy脚本,具体目录已经脚本入如下图所示
在这里插入图片描述
打开文件,在里面编辑脚本

ctx._source.tags+=new_tag

然后回到kibana,在那里提交修改的命令:

POST /test_index/test_type/11/_update
{
 "script": {
   "lang": "groovy", 				#设置语言
   "file": "test-add-tags",		#文件名
   "params": {						#参数
     "new_tag": "tag1"
   }
 }
}

然后再运行get请求,你就会发现,这个document下tags字段多了一个tag1
在这里插入图片描述

3.用脚本删除文档

与前一章一样,新建脚本test-delete-document.groovy并编辑:

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

然后发送请求:

POST /test_index/test_type/11/_update
{
  "script": {
    "lang": "groovy",
    "file": "test-delete-document",
    "params": {
      "count": 1
    }
  }
}

执行命令后,再去get这个document,发现这个文档已经被删除了

4. upsert操作

基于刚刚上面几步操作的document,因为我们已经把它删除了,再运行update的命令,是会报错的

POST /test_index/test_type/11/_update
{
  "doc": {
    "num": 1
  }
}

{
  "error": {
    "root_cause": [
      {
        "type": "document_missing_exception",
        "reason": "[test_type][11]: document missing",
        "index_uuid": "6m0G7yx7R1KECWWGnfH1sw",
        "shard": "4",
        "index": "test_index"
      }
    ],
    "type": "document_missing_exception",
    "reason": "[test_type][11]: document missing",
    "index_uuid": "6m0G7yx7R1KECWWGnfH1sw",
    "shard": "4",
    "index": "test_index"
  },
  "status": 404
}

运行upsert

POST /test_index/test_type/11/_update
{
   "script" : "ctx._source.num+=1",
   "upsert": {
       "num": 0,
       "tags": []
   }
}

注:如果指定的document不存在,就执行upsert中的初始化操作;如果指定的document存在,就执行doc或者script指定的partial update操作

什么意思呢?就是说现在跑上面的请求,会进行初始或操纵,不会去运行script脚本,只有再document存在的时候,才会去跑,才会对num字段进行修改

猜你喜欢

转载自blog.csdn.net/qq_34646817/article/details/87875202