You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elasticsearch 6.8:如何用grok与foreach生成正确嵌套字段

Elasticsearch 6.8 Ingest Pipeline 生成嵌套数组字段问题解决

你当前的问题核心是foreach处理器每次迭代会覆盖提取的字段值,导致最后set处理器只能拿到最后一次迭代的结果。要解决这个问题,需要在每次迭代时将提取的对象追加到目标数组,而不是最后一次性赋值。

以下是修正后的完整Ingest Pipeline:

PUT _ingest/pipeline/info_pipeline
{
  "description": "将info字段解析为information_nested嵌套数组",
  "processors": [
    {
      "grok": {
        "field": "_source.info",
        "patterns": [
          "Information: \\[%{DATA:information}\\] end"
        ]
      }
    },
    {
      "split": {
        "field": "information",
        "separator": ", "
      }
    },
    {
      "foreach": {
        "field": "information",
        "processor": [
          {
            "grok": {
              "field": "_ingest._value",
              "patterns": [
                "Books:%{NUMBER:temp_books:int}\\tPencils:%{NUMBER:temp_pencils:int}\\tPens:%{NUMBER:temp_pens:int}"
              ]
            }
          },
          {
            "append": {
              "field": "information_nested",
              "value": {
                "books": "{{temp_books}}",
                "pencils": "{{temp_pencils}}",
                "pens": "{{temp_pens}}"
              }
            }
          },
          {
            "remove": {
              "field": ["temp_books", "temp_pencils", "temp_pens"]
            }
          }
        ]
      }
    },
    {
      "remove": {
        "field": "information"
      }
    }
  ]
}

关键修改说明:

  1. 使用临时字段避免覆盖:把grok提取的字段命名为temp_books、temp_pencils、temp_pens,防止不同迭代之间的字段值互相覆盖。
  2. 用append替代最后一次性set:在每次foreach迭代中,通过append处理器将当前提取的对象添加到information_nested数组中。append会自动创建数组(如果字段不存在),并持续追加元素。
  3. 清理临时字段:每次迭代后删除临时字段,避免残留不必要的数据。

经过上述修改,处理后的文档会生成包含三个对象的information_nested嵌套数组,与你的期望输出一致。

内容的提问来源于stack exchange,提问作者Zeus29

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 03:25:18