首页 > 解决方案 > 在 Elasticsearch Painless Lab 中定义一组 json 文档

问题描述

我试图在 ES Painless Lab中定义一些文档,在 Painless Lab中测试一些逻辑,然后在实际索引上运行它,但无法弄清楚如何去做,文档也没有帮助。关于实际语法的文档很少,对于没有 Java 背景的人来说帮助不大。

如果我尝试定义这样的文档:

def docs = [{ "id": 1, "name": "Apple" }];

我收到一个错误:

Unhandled Exception illegal_argument_exception

invalid sequence of tokens near ['{'].

Stack:
[
  "def docs = [{ \"id\": 1, \"name\": \"Apple ...",
  "          ^---- HERE"
]

如果我想用Java 方式来做:

String message;
JSONObject json = new JSONObject();

json.put("test1", "value1");

message = json.toString();

我也收到一个错误:

Unhandled Exception illegal_argument_exception

invalid declaration: cannot resolve type [JSONObject]

Stack:
[
  "... ring message;\nJSONObject json = new JSONObject();\n ...",
  "                             ^---- HERE"
]

那么在 Painless Lab 中定义要使用的 json 对象数组的正确方法是什么?

标签: elasticsearchelasticsearch-painless

解决方案


经过更多的实验,我发现文档可以在参数选项卡中传递为:

{
  "docs": [
    { "id": 1, "name": "Apple" },
    { "id": 2, "name": "Pear" },
    { "id": 3, "name": "Pineapple" }
  ]
}

然后从代码中访问它

def doc = params.docs[1];
return doc["name"];

我仍然对如何在代码本身中定义对象或数组感兴趣。


推荐阅读