我如何在 Elasticsearch 的无痛脚本中使用 Java 的 ArrayList class?

How can i use Java's ArrayList class in painless script of Elasticsearch?

我想在 elasticsearch 中为 script_score 编写一个脚本。

Painless Documentation 中有 java class 的列表在 "Shared api reference" 下。

GET hockey/_search
{
  "explain": true, 
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "total_goals": {
      "script": {
        "lang": "painless",
        "source": """

          int[] arr = new int[3];
          arr[0] = 1;
          arr[1] = 2;
          arr[2] = 3;
          return arr;

        """,
        "params":{
          "last" : "any parameters required"
        }

      }
    }
  }
}

以上脚本按预期工作。但我想改用 Java 的 ArrayList 或其他一些 Class。

GET hockey/_search
{
  "explain": true, 
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "total_goals": {
      "script": {
        "lang": "painless",
        "source": """
          ArrayList<Integer> al = new ArrayList<Integer>();
          al.add(1);
          al.add(2);
          return al;

        """,
        "params":{
          "last" : "any parameters required"
        }

      }
    }
  }
}

这会引发以下错误。

{
  "error" : {
    "root_cause" : [
      {
        "type" : "script_exception",
        "reason" : "compile error",
        "script_stack" : [
          "\n          ArrayList<Integer> al = new ArrayL ...",
          "                    ^---- HERE"
        ],
        "script" : "\n          ArrayList<Integer> al = new ArrayList<Integer>();\n          al.add(1);\n          al.add(2);\n          return al;\n          \n        ",
        "lang" : "painless"
      }
    ],
    "type" : "search_phase_execution_exception",
    "reason" : "all shards failed",
    "phase" : "query",
    "grouped" : true,
    "failed_shards" : [
      {
        "shard" : 0,
        "index" : "hockey",
        "node" : "UIMgEAZNRzmIpRGyQtNk9g",
        "reason" : {
          "type" : "script_exception",
          "reason" : "compile error",
          "script_stack" : [
            "\n          ArrayList<Integer> al = new ArrayL ...",
            "                    ^---- HERE"
          ],
          "script" : "\n          ArrayList<Integer> al = new ArrayList<Integer>();\n          al.add(1);\n          al.add(2);\n          return al;\n          \n        ",
          "lang" : "painless",
          "caused_by" : {
            "type" : "illegal_argument_exception",
            "reason" : "invalid sequence of tokens near ['<'].",
            "caused_by" : {
              "type" : "no_viable_alt_exception",
              "reason" : null
            }
          }
        }
      }
    ]
  },
  "status" : 400
}

如果可以使用 ArrayList class 那么,

我必须从 java.util 导入它吗?

您可以使用 ArrayList al = new ArrayList(); 或什至只是 def al = new ArrayList(); docs 中的更多信息。

仅供参考:您可以使用 Debug.explain(al); 来检查是什么!