Search code examples
elasticsearchelasticsearch-painless

Painless access a value in an ArrayList


Trying to work out how to access an item in an ArrayList.

I have the values in _source:

  "session_id" : [
    "19a7ec8d",
    "19a7ec8d"
  ],

As they are all duplicates (due to a faulty Grok script), I want to get rid of the duplicates:

I cannot workout how to access the value.

String old = ctx._source.session_id[0];
ctx._source.remove(\"session_id\");
ctx._source.session_id = old;

I have also tried:

String old = ctx._source.session_id.get(0);

String old = ctx._source.session_id.get(0).value()

String old = ctx._source.session_id[0].value()

String old = ctx._source.session_id.get(0).toString()

Thanks


Solution

  • You can use _update_by_query

    Data:

    "hits" : [
          {
            "_index" : "index7",
            "_type" : "_doc",
            "_id" : "zQPYkXEB9JyZpSui0FLw",
            "_score" : 1.0,
            "_source" : {
              "session_id" : [
                "19a7ec8d",
                "19a7ec8d"
              ]
            }
          }
        ]
    

    Query:

    POST index7/_update_by_query
    {
      "script":{
        "source":"if(ctx._source.session_id instanceof List && ctx._source.session_id.size()>0) { def firstValue=ctx._source.session_id[0];ctx._source.session_id=firstValue;}"
      },
      "query":{
        "match_all":{} 
      }
    }
    

    Result:

    "hits" : [
          {
            "_index" : "index7",
            "_type" : "_doc",
            "_id" : "zQPYkXEB9JyZpSui0FLw",
            "_score" : 1.0,
            "_source" : {
              "session_id" : "19a7ec8d"
            }
          }
        ]