ElasticSearch入门玩转大数据elasticsearch

二十三、Elasticsearch基于groovy脚本进行par

2017-07-06  本文已影响531人  编程界的小学生

1、简单解释:
ES其实是有个内置的脚本支持的,可以基于groovy脚本实现各种的复杂操作,基于groovy脚本,如何执行partial update?(这里只是初步讲解下,深入的讲解后期会说,此篇只是带大家入个门)

2、数据准备

PUT /test_index/test_type/11
{
  "num" : 0,
  "tags" : []
}

3、内置脚本

需求:将num值进行+=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": []
  }
}

num值已经变成了1

4、外部脚本

需求:每次都给tags动态添加一个自定义的值

步骤:
(1)在ES安装包下的config\scripts下创建个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"
    }
  }
}

查询结果:

{
  "_index": "test_index",
  "_type": "test_type",
  "_id": "11",
  "_version": 3,
  "found": true,
  "_source": {
    "num": 1,
    "tags": [
      "tag1"
    ]
  }
}

5、外部脚本删除文档
步骤:
(1)在ES安装包下的config\scripts下创建个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
    }
  }
}

执行查询,查询结果

{
  "_index": "test_index",
  "_type": "test_type",
  "_id": "11",
  "found": false
}

已经被删了

6、upsert操作
接着上步骤已经删除的11继续操作

只更新num字段

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
}

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

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

结果:

{
  "_index": "test_index",
  "_type": "test_type",
  "_id": "11",
  "_version": 1,
  "result": "created",
  "_shards": {
    "total": 2,
    "successful": 2,
    "failed": 0
  }
}

发现

"_version": 1,
  "result": "created",

证明是upsert执行新增操作。而script没有执行。查询一下
GET /test_index/test_type/11
结果

{
  "_index": "test_index",
  "_type": "test_type",
  "_id": "11",
  "_version": 1,
  "found": true,
  "_source": {
    "num": 0,
    "tags": []
  }
}

若有兴趣,欢迎来加入群,【Java初学者学习交流群】:458430385,此群有Java开发人员、UI设计人员和前端工程师。有问必答,共同探讨学习,一起进步!
欢迎关注我的微信公众号【Java码农社区】,会定时推送各种干货:


qrcode_for_gh_577b64e73701_258.jpg
上一篇 下一篇

猜你喜欢

热点阅读