Link Search Menu Expand Document Documentation Menu

Foreach 处理器

foreach 处理器用于迭代输入文档中的值列表,并对每个值应用转换。这对于一致地处理数组中的所有元素(例如,将字符串中的所有元素转换为小写或大写)非常有用。

以下是 foreach 处理器的语法:

{
  "foreach": {
    "field": "<field_name>",
    "processor": {
      "<processor_type>": {
        "<processor_config>": "<processor_value>"
      }
    }
  }
}

配置参数

下表列出了 foreach 处理器所需和可选的参数。

参数 必需/可选 描述
字段 必需 要迭代的数组字段。
处理器 必需 针对每个字段执行的处理器。
忽略缺失 可选 如果为 true 且指定字段不存在或为空,则处理器将静默退出,而不修改文档。
描述 可选 处理器的简要描述。
if 可选 运行处理器的条件。
忽略失败 可选 指定即使处理器遇到错误是否继续执行。如果设置为 true,则忽略失败。默认值为 false
失败时 可选 处理器失败时要运行的处理器列表。
标签 可选 处理器的标识符标签。有助于调试以区分相同类型的处理器。

使用处理器

按照以下步骤在管道中使用处理器。

步骤 1:创建管道

以下查询创建了一个名为 test-foreach 的管道,该管道使用 foreach 处理器迭代 protocols 字段中的每个元素:

PUT _ingest/pipeline/test-foreach  
{  
  "description": "Lowercase all the elements in an array",  
  "processors": [  
    {  
      "foreach": {  
        "field": "protocols",  
        "processor": {  
          "lowercase": {  
            "field": "_ingest._value"  
          }  
        }  
      }  

步骤 2(可选):测试管道

建议在摄取文档之前测试您的管道。

要测试管道,请运行以下查询

POST _ingest/pipeline/test-foreach/_simulate  
{  
  "docs": [  
    {  
      "_index": "testindex1",  
      "_id": "1",  
      "_source": {  
        "protocols": ["HTTP","HTTPS","TCP","UDP"]  
      }  
    }  
  ]  
} 

响应

以下示例响应确认管道按预期工作,显示四个元素已转换为小写:

{  
  "docs": [  
    {  
      "doc": {  
        "_index": "testindex1",  
        "_id": "1",  
        "_source": {  
          "protocols": [  
            "http",  
            "https",  
            "tcp",  
            "udp"  
          ]  
        },  
        "_ingest": {  
          "_value": null,  
          "timestamp": "2024-05-23T02:44:10.8201Z"  
        }  
      }  
    }  
  ]  
}  

步骤 3:摄取文档

以下查询将文档摄取到名为 testindex1 的索引中

POST testindex1/_doc/1?pipeline=test-foreach  
{  
  "protocols": ["HTTP","HTTPS","TCP","UDP"]  
}  

响应

该请求将文档索引到 testindex1 索引中,并在索引前应用管道。

{  
  "_index": "testindex1",  
  "_id": "1",  
  "_version": 6,  
  "result": "created",  
  "_shards": {  
    "total": 2,  
    "successful": 1,  
    "failed": 0  
  },  
  "_seq_no": 5,  
  "_primary_term": 67  
}  

步骤 4(可选):检索文档

要检索文档,请运行以下查询

GET testindex1/_doc/1

响应

响应显示了包含从 users 字段中提取的 JSON 数据的文档。

{  
  "_index": "testindex1",  
  "_id": "1",  
  "_version": 6,  
  "_seq_no": 5,  
  "_primary_term": 67,  
  "found": true,  
  "_source": {  
    "protocols": [  
      "http",  
      "https",  
      "tcp",  
      "udp"  
    ]  
  }  
}  

{  
  "docs": [  
    {  
      "doc": {  
        "_index": "testindex1",  
        "_id": "1",  
        "_source": {  
          "protocols": [  
            "http",  
            "https",  
            "tcp",  
            "udp"  
          ]  
        },  
        "_ingest": {  
          "_value": null,  
          "timestamp": "2024-05-23T02:44:10.8201Z"  
        }  
      }  
    }  
  ]  
}  

剩余 350 字符

有问题?

想要贡献?