关于ElasticSearch使用Groovy做局部更新出现问题:Variable [new_tag] is not defined.

遇见问题特此记录希望能帮助到看到的人

在跟着ElasticSearch权威指南学习过程中依旧发现有些语句是不再支持的
在局部更新一节,依照Demo
当前的数据索引结果是这样的:
{
    _index: "website",
    _type: "blog",
    _id: "123",
    _version: 5,
    found: true,
    _source: {
        title: "Myfirstblogentry",
        text: "Iamstartingtogetthehangofthis...",
        date: "2014/01/02",
        views: 0,
        tags: [
            "testing",
        ]
    }
}

现更新views的值使用语句

curl -H "Content-Type:application/json" -XOST 127.0.0.1:9200/website/blog/123/_update?pretty -d '"script" : "ctx._source.views+=1"'

当然结果是没有问题的,views字段变为1,但是按照指南下在tags数组里增添成员时出现问题

原ElasticSearch权威指南增添语句

POST /website/blog/1/_update
{
   "script" : "ctx._source.tags+=new_tag",
   "params" : {
      "new_tag" : "search"
   }
}

报出异常信息:

HTTP/1.1 400 Bad Request
content-type: application/json; charset=UTF-8
content-length: 693


{
  "error" : {
    "root_cause" : [
      {
        "type" : "remote_transport_exception",
        "reason" : "[node-1][10.135.185.246:9300][indices:data/write/update[s]]"
      }
    ],
    "type" : "illegal_argument_exception",
    "reason" : "failed to execute script",
    "caused_by" : {
      "type" : "script_exception",
      "reason" : "compile error",
      "script_stack" : [
        "ctx._source.tags+=new_tag",
        " ^---- HERE"
      ],
      "script" : "ctx._source.tags+=new_tag",
      "lang" : "painless",
      "caused_by" : {
        "type" : "illegal_argument_exception",
        "reason" : "Variable [new_tag] is not defined." }
    }
  },
  "status" : 400
}

从字面意义上理解为未找到new_tag的定义
这里在网上找了找是需要指定new_tag出现的位置,须加前缀为:params.new_tag
更改后的caused_by变为

      "caused_by" : {
        "type" : "null_pointer_exception",
        "reason" : null
      }

并且tags内容变为

tags: [
    "testing",
    null
]

这就很奇怪了,添加进去一个null????????
后来在stackoverflow上找到答案,原文地址:
https://stackoverflow.com/questions/43079189/elasticsearch-script-variable-not-defined#
语法需要变为add()函数,同时也要指明params域下的new_tags

curl -XGET 127.0.0.1i -H "Content-Type:application/json" -XPOST 127.0.0.1:9200/website/blog/123/_update?pretty -d '{"script":{"inline":"ctx._source.tags.add(params.new_tag)","params":{"new_tag":"search"}}}'

再search一下发现是成功add的

{
    _index: "website",
    _type: "blog",
    _id: "123",
    _version: 8,
    found: true,
    _source: {
        title: "Myfirstblogentry",
        text: "Iamstartingtogetthehangofthis...",
        date: "2014/01/02",
        views: 1,
        tags: [
            "testing",
            "search"
        ]
    }
}

遇到的问题大多都能百度或者Google的,希望大家都能圆满解决问题
如果这篇文章帮助到你,点个赞呗~

你可能感兴趣的:(ElasticSearch,大数据,elasticsearch)