2

I want to write a painless script which should return a dictionary. Basically, If I relate it to java, I want an output of Dictionary< String, List >.

So, I need to declare a Map and List in painless. Also, I need to add data to it (like map.add())

Can I have an example how would you declare a map and add data to it?

The examples at [painless] (https://www.elastic.co/guide/en/elasticsearch/painless/6.7/painless-examples.html) does not cover this.

I am using v6.7

AbhiArora
  • 162
  • 1
  • 8

1 Answers1

6

You can do it simply like this:

Create the document with an empty dictionary

PUT index/1
{
  "dict": {}
}

Update the document to fill the dictionary in parameter

POST index/_update/1
{
    "script" : {
        "source": "ctx._source.dict.putAll(params)",
        "lang": "painless",
        "params" : {
            "key1": ["val1", "val2", "val3"],
            "key2": ["val4", "val5"]
        }
    }
}

You can also index the document from scratch using a script (with scripted_upsert)

POST index/_update/1
{
    "scripted_upsert":true,
    "script" : {
        "source": """
          ctx._source.dict = [:];
          ctx._source.dict['key1'] = params.key1;
          ctx._source.dict['key2'] = params.key2;
        """,
        "params" : {
            "key1" : ["val1", "val2", "val3"],
            "key2" : ["val1", "val2", "val3"]
        }
    },
    "upsert" : {}
}

In both cases, you'll end up with a document like this:

GET /index/1

{
  "dict": {
      "key1" : ["val1", "val2", "val3"],
      "key2" : ["val1", "val2", "val3"]
  }
}
Val
  • 207,596
  • 13
  • 358
  • 360
  • This seems like a nice workaround of the requirement but i got stuck at one point. Earlier I was thinking to write a _search api and output the desired result. But now, if I have to write an update api, how can I possibly query index-A and document A1 and update the results to index-B document B1? If I mention index name(A) in the url, how can I update a document in index (B) ? – AbhiArora May 28 '19 at 04:43
  • You need to do it with two requests – Val May 28 '19 at 05:59
  • I found these docs helpful: https://www.elastic.co/guide/en/elasticsearch/painless/master/painless-api-reference-shared-java-util.html – DharmaTurtle May 21 '21 at 23:41