使用Elasticsearch并轻松进行,如何插入地图数组?

时间:2019-04-26 02:05:16

标签: elasticsearch elasticsearch-painless

我有以下代码:

  "script": {
    "lang": "painless",
    "source": """
      ctx._source.maparray = [
    "first" : "Foo",
    "last" : "Bar"
]

结果

"maparray": {
  "last": "Bar",
  "first": "Foo"
},

但是我希望maparray是一个数组。所以现在基于:

https://www.elastic.co/guide/en/elasticsearch/painless/current/painless-operators-array.html

我尝试:

 "script": {
    "lang": "painless",
    "source": """
      ctx._source.maparray = new map[]{[
    "first" : "Foo",
    "last" : "Bar"
]}
    """,
    "params": {
      "key": "numWords"
    }
  }

但是我得到了

{
  "error": {
    "root_cause": [
      {
        "type": "script_exception",
        "reason": "compile error",
        "script_stack": [
          "... x._source.maparray = new map[]{[\n    \"first\" : \"Fo ...",
          "                             ^---- HERE"
        ],
        "script": "      ctx._source.maparray = new map[]{[\n    \"first\" : \"Foo\",\n    \"last\" : \"Bar\"\n]}",
        "lang": "painless"
      }
    ],
    "type": "script_exception",
    "reason": "compile error",
    "script_stack": [
      "... x._source.maparray = new map[]{[\n    \"first\" : \"Fo ...",
      "                             ^---- HERE"
    ],
    "script": "      ctx._source.maparray = new map[]{[\n    \"first\" : \"Foo\",\n    \"last\" : \"Bar\"\n]}",
    "lang": "painless",
    "caused_by": {
      "type": "illegal_argument_exception",
      "reason": "invalid sequence of tokens near ['map'].",
      "caused_by": {
        "type": "no_viable_alt_exception",
        "reason": null
      }
    }
  },
  "status": 500
}

我的语法有什么问题?

1 个答案:

答案 0 :(得分:0)

您要寻找的实际上是一组地图。下面是我在使用Ingest Pipeline的地方编写示例脚本的方式。

带脚本的必需管道

PUT _ingest/pipeline/my-pipeline-id-01
{
  "description" : "describe pipeline",
  "processors" : [
    {
        "script" : {
          "lang" : "painless",
          "inline" : """
             ArrayList al = new ArrayList();
             Map map = new HashMap();
             map.put("first","Foo");
             map.put("last", "Bar");
             al.add(map);
             ctx.maparray = al;
            """
        }
      }
  ]
}

您可以使用Reindex API测试脚本的工作方式。

重新编制索引脚本

POST _reindex
{
  "source": {
    "index": "<source_index_name>"
  },
  "dest": {
    "index": "<dest_index_name>",
    "pipeline": "my-pipeline-id-01"
  }
}

请对以上内容进行测试,并验证结果,然后告诉我如何进行。

希望这会有所帮助!