使用 Painless 在 Elastic 文档上设置硬编码值

Setting a hardcoded value on an Elastic document with Painless

我正在尝试学习 Painless,以便在尝试丰富和处理传入文档时可以使用它。但是,我所看到的访问文档的每一种方式都会导致错误。 在 Kibana 的 Painless Lab 中输入这个后,这些是我得到的错误:

def paths = new String[3];
paths[0]= '.com';
paths[1] = 'bar.com';
paths[2] = 'foo.bar.com';
doc['my_field'] = paths;  // does not work: '[Ljava.lang.String; cannot be cast to org.elasticsearch.index.fielddata.ScriptDocValues'
ctx.my_field = paths;  // does not compile: 'cannot resolve symbol [ctx.my_field]'
return doc['my_field'] == 'field_value';  // does not work: 'No field found for [my_field] in mapping'

doc['my_field'] == 'field_value' 抱怨尽管该字段存在于测试文档中,但 doc.containsKey('my_field') 确实 return false.

我实际上应该如何访问和处理传入的文档?我正在使用 ElasticSearch 7.12。

您可以创建 ingest pipeline with set processor 以向传入文档添加硬编码值。

{
  "description" : "sets the value of count to 1",
  "set": {
    "field": "count",
    "value": 1
  }
}

有非常具体的context available for painless API. you are using String[] which may be causing issue so you need to use either Arrays or ArraysList. you can check example of painless lab here

以下是我在无痛实验室中尝试过的脚本,它按预期工作:

def ctx = params.ctx;
ArrayList paths = new ArrayList();
paths.add('.com');
paths.add('bar.com');
paths.add('foo.bar.com');
ctx['my_field'] = paths;
return ctx

在下面的参数选项卡中添加,我错过了在答案中添加它。这是必需的,因为在实际实施中,您将从上下文中获取价值并更新上下文。

{
  "ctx":{
    "my_field":["test"]
  }
}