我正在关注 Elasticsearch tutorial ,但在脚本中尝试使用参数时遇到了问题。
第 1 步:创建新文档 - 确定 (index = website; type = blog; id = 1
)
curl -XPUT localhost:9200/website/blog/1?pretty -d '{
"title":"my first post",
"tags" : [ "tag1" ]
}'
第 2 步:使用脚本将额外值附加到 tags
数组 - 错误
curl -XPOST localhost:9200/website/blog/1/_update?pretty -d '{
"script" : "ctx._source.tags+=new_tag",
"params" : {
"new_tag" : "tag2"
}
}'
错误信息是这样的,提到“原因”:“变量[new_tag]未定义。”
但是我已经按照教程中的描述定义了变量new_tag
页。我做错了什么?
"error" : {
"root_cause" : [
{
"type" : "remote_transport_exception",
"reason" : "[mrukUvA][127.0.0.1:9300][indices:data/write/update[s]]"
}
],
"type" : "illegal_argument_exception",
"reason" : "failed to execute script",
"caused_by" : {
"type" : "script_exception",
"reason" : "compile error",
"caused_by" : {
"type" : "illegal_argument_exception",
"reason" : "Variable [new_tag] is not defined."
},
"script_stack" : [
"ctx._source.tags+=new_tag",
" ^---- HERE"
],
"script" : "ctx._source.tags+=new_tag",
"lang" : "painless"
}
},
"status" : 400
}
第 2 步(重试)使用 params
限定 new_tag
- 错误
curl -XPOST localhost:9200/website/blog/1/_update?pretty -d '{
"script" : {
"inline": "ctx._source.tags+=params.new_tag",
"params" : {
"new_tag" : "tag2"
}
}
}'
给出错误
{
"error" : {
"root_cause" : [
{
"type" : "remote_transport_exception",
"reason" : "[mrukUvA][127.0.0.1:9300][indices:data/write/update[s]]"
}
],
"type" : "illegal_argument_exception",
"reason" : "failed to execute script",
"caused_by" : {
"type" : "script_exception",
"reason" : "runtime error",
"caused_by" : {
"type" : "class_cast_exception",
"reason" : "Cannot cast java.lang.String to java.util.ArrayList"
},
"script_stack" : [
"ctx._source.tags+=params.new_tag",
" ^---- HERE"
],
"script" : "ctx._source.tags+=params.new_tag",
"lang" : "painless"
}
},
"status" : 400
}
作为完整性检查以确保文档有效
$ curl -XGET localhost:9200/website/blog/1?pretty
{
"_index" : "website",
"_type" : "blog",
"_id" : "1",
"_version" : 27,
"found" : true,
"_source" : {
"title" : "my first post",
"tags" : [
"tag1"
]
}
}
因此文档确实具有有效字段 tag
,它是一个数组。
最佳答案
您的语法略有偏差,如果您有参数,则需要内联
脚本。试试这个:
curl -XPOST localhost:9200/website/blog/1/_update?pretty -d '{
"script" : {
"inline": "ctx._source.tags.add(params.new_tag)",
"params" : {
"new_tag" : "tag2"
}
}
}'
关于Elasticsearch 脚本 - undefined variable ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43079189/