无痛访问 ArrayList 中的值

Painless access a value in an ArrayList

正在尝试找出如何访问 ArrayList 中的项目。

我在 _source 中有这些值:

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

因为它们都是重复的(由于错误的 Grok 脚本),我想摆脱重复:

我不知道如何访问该值。

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

我也试过:

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()

谢谢

您可以使用_update_by_query

数据:

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

查询:

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":{} 
  }
}

结果:

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

使数组项唯一的通用方法:

GET index7/_update_by_query
{
  "query": {
    "bool": {
      "filter": {
        "exists": {
          "field": "session_id"
        }
      }
    }
  },
  "script": {
    "inline": """ctx._source.session_id = ctx._source
                                            .session_id
                                            .stream()
                                            .sorted()
                                            .collect(Collectors.toList());
                                            """
  }
}