代码之家  ›  专栏  ›  技术社区  ›  bokan

在ElasticSearch中,如何将对象数组转换为字符串数组?

  •  0
  • bokan  · 技术社区  · 8 年前

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

    {
       "name":"John Doe",
       "sport":[
           {
              "name":"surf",
              "since":"2 years"
           },
           {
              "name":"mountainbike",
              "since":"4 years"
           },
       ]
    }
    

    如何放弃“自”信息,这样一旦重新索引对象将只包含运动名称?这样地:

    {
       "name":"John Doe",
       "sport":["surf","mountainbike"]
    }
    

    请注意,如果结果字段保持相同的名称,这是可以的,但它不是必需的。

    1 回复  |  直到 8 年前
        1
  •  2
  •   ThomasC    8 年前

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

    • 1)A script 处理器用于从每个子对象中提取值并将其设置在另一个字段中(此处, sports )
    • 2)上一个 sport 字段用删除 remove 处理器

    您可以使用 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"
              }
            ]
          }
        }
      ]
    }
    

    输出以下结果:

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

    可能有更好的解决方案,因为我没有经常使用管道,或者您可以在将文档提交到您的ElasticSearch集群之前使用logstash过滤器来实现这一点。

    有关管道的更多信息,请查看 reference documentation of ingest nodes .