Link Search Menu Expand Document Documentation Menu

Trim 处理器

trim 处理器用于从指定字段中移除开头和结尾的空白字符。

以下是 trim 处理器的语法:

{
  "trim": {
    "field": "field_to_trim",
    "target_field": "trimmed_field"
  }
}

配置参数

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

参数 必需/可选 描述
field 必需 包含要修剪文本的字段。
target_field 必需 存储修剪后文本的字段。如果未指定,则就地更新字段。
ignore_missing 可选 指定处理器是否应忽略不包含指定字段的文档。如果设置为 true,则处理器会忽略字段中缺失的值,并保持 target_field 不变。默认值为 false
description 可选 处理器的简要描述。
if 可选 运行处理器的条件。
ignore_failure 可选 指定即使遇到错误,处理器是否继续执行。如果设置为 true,则忽略失败。默认值为 false
on_failure 可选 处理器失败时要运行的处理器列表。
tag 可选 处理器的标识符标签。有助于调试以区分相同类型的处理器。

使用处理器

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

步骤 1:创建管道

以下查询创建了一个名为 trim_pipeline 的管道,该管道使用 trim 处理器从 raw_text 字段中移除开头和结尾的空白字符,并将修剪后的文本存储在 trimmed_text 字段中:

PUT _ingest/pipeline/trim_pipeline
{
  "description": "Trim leading and trailing white space",
  "processors": [
    {
      "trim": {
        "field": "raw_text",
        "target_field": "trimmed_text"
      }
    }
  ]
}

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

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

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

POST _ingest/pipeline/trim_pipeline/_simulate
{
  "docs": [
    {
      "_source": {
        "raw_text": "   Hello, world!   "
      }
    }
  ]
}

响应

以下示例响应确认管道按预期工作

{
  "docs": [
    {
      "doc": {
        "_index": "_index",
        "_id": "_id",
        "_source": {
          "raw_text": "   Hello, world!   ",
          "trimmed_text": "Hello, world!"
        },
        "_ingest": {
          "timestamp": "2024-04-26T20:58:17.418006805Z"
        }
      }
    }
  ]
}

步骤 3:摄取文档

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

PUT testindex1/_doc/1?pipeline=trim_pipeline
{
  "message": "   This is a test document.   "
}

响应

该请求将文档索引到 testindex1 索引中,并索引所有包含 raw_text 字段的文档,这些文档由 trim_pipeline 处理,以填充 trimmed_text 字段,如下面的响应所示:

  "_index": "testindex1",
  "_id": "1",
  "_version": 68,
  "result": "updated",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "_seq_no": 70,
  "_primary_term": 47
}

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

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

GET testindex1/_doc/1

响应中包含已移除开头和结尾空白字符的 trimmed_text 字段

{
  "_index": "testindex1",
  "_id": "1",
  "_version": 69,
  "_seq_no": 71,
  "_primary_term": 47,
  "found": true,
  "_source": {
    "raw_text": "   This is a test document.   ",
    "trimmed_text": "This is a test document."
  }
}
剩余 350 字符

有问题?

想做贡献?