在elasticsearch中重新索引时如何将对象数组转换为字符串数组?

bok*_*kan 1 elasticsearch

假设源索引有一个这样的文档:

{
   "name":"John Doe",
   "sport":[
       {
          "name":"surf",
          "since":"2 years"
       },
       {
          "name":"mountainbike",
          "since":"4 years"
       },
   ]
}
Run Code Online (Sandbox Code Playgroud)

如何丢弃“因为”信息,以便一旦重新索引对象将只包含运动名称?像这样 :

{
   "name":"John Doe",
   "sport":["surf","mountainbike"]
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果结果字段保持相同的名称就可以了,但这不是强制性的。

Tho*_*asC 5

我不知道您使用的是哪个版本的 elasticsearch,但这里有一个基于pipelines的解决方案,在 ES v5.0 中引入了摄取节点。

  • 1)script处理器用于从每个子对象中提取值并将其设置在另一个字段中(此处为sports
  • 2)sportremove处理器去掉前面的字段

您可以使用Simulate pipeline API来测试它:

POST _ingest/pipeline/_simulate
{
  "pipeline": {
    "description": "random description",
    "processors": [
      {
        "script": {
          "lang": "painless",
          "source": "ctx.sports =[]; for (def item : ctx.sport) { ctx.sports.add(item.name)  }"
        }
      },
      {
        "remove": {
          "field": "sport"
        }
      }
    ]
  },
  "docs": [
    {
      "_index": "index",
      "_type": "doc",
      "_id": "id",
      "_source": {
        "name": "John Doe",
        "sport": [
          {
            "name": "surf",
            "since": "2 years"
          },
          {
            "name": "mountainbike",
            "since": "4 years"
          }
        ]
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

输出以下结果:

{
  "docs": [
    {
      "doc": {
        "_index": "index",
        "_type": "doc",
        "_id": "id",
        "_source": {
          "name": "John Doe",
          "sports": [
            "surf",
            "mountainbike"
          ]
        },
        "_ingest": {
          "timestamp": "2018-07-12T14:07:25.495Z"
        }
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

可能有更好的解决方案,因为我没有经常使用管道,或者您可以在将文档提交到 Elasticsearch 集群之前使用 Logstash 过滤器进行设置。

有关管道的更多信息,请查看摄取节点参考文档