Search code examples
elasticsearchelasticsearch-painless

Setting a hardcoded value on an Elastic document with Painless


I'm trying to learn Painless so that I could use it while trying to enrich and manipulate incoming documents. However, every way I've seen for accessing the document just results in errors. Having input this in the Painless Lab in Kibana, these are the errors I'm getting:

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' complains despite the field being present in the test document, though doc.containsKey('my_field') does return false.

How should I actually be accessing and manipulating the incoming document? I'm using ElasticSearch 7.12.


Solution

  • You can create ingest pipeline with set processor for adding hardcode value to incoming document.

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

    There are very specific 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.

    Below is script i have tried in painless lab and it is working as expcted:

    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
    

    enter image description here

    Add below in parameters tab, i missed to add this in answer. this required because in actual implmentation you will get value from context and update context.

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