Link Search Menu Expand Document Documentation Menu

排序处理器

sort 处理器以升序或降序对项目数组进行排序。数值数组按数字排序,而字符串或混合数组(字符串和数字)按字典顺序排序。如果输入不是数组,处理器将抛出错误。

以下是 sort 处理器的语法

{
  "description": "Sort an array of items",
  "processors": [
    {
      "sort": {
        "field": "my_array_field",
        "order": "desc"
      }
    }
  ]
}

配置参数

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

参数 必需/可选 描述
字段 必需 要排序的字段。必须是数组。
顺序 可选 要应用的排序顺序。接受 asc 表示升序,desc 表示降序。默认为 asc
目标字段 可选 存储排序后数组的字段名称。如果未指定,则排序后的数组将存储在与原始数组(field 变量)相同的字段中。
描述 可选 处理器的目的或配置说明。
if 可选 指定条件性执行处理器。
忽略失败 可选 指定是否忽略处理器故障。请参阅处理管道故障
失败时 可选 指定在处理器执行失败时运行的处理器列表。这些处理器按照指定的顺序执行。
标签 可选 处理器的标识符标签。有助于调试以区分相同类型的处理器。

使用处理器

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

步骤 1:创建管道

以下查询创建了一个名为 sort-pipeline 的管道,该管道使用 sort 处理器按降序排序 my_field 并将排序后的值存储在 sorted_field

PUT _ingest/pipeline/sort-pipeline
{
  "description": "Sort an array of items in descending order",
  "processors": [
    {
      "sort": {
        "field": "my_array_field",
        "order": "desc",
        "target_field": "sorted_array"
      }
    }
  ]
}

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

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

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

POST _ingest/pipeline/sort-pipeline/_simulate
{
  "docs": [
    {
      "_source": {
        "my_array_field": [3, 1, 4, 1, 5, 9, 2, 6, 5]
      }
    }
  ]
}

响应

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

{
  "docs": [
    {
      "doc": {
        "_index": "_index",
        "_id": "_id",
        "_source": {
          "sorted_array": [
            9,
            6,
            5,
            5,
            4,
            3,
            2,
            1,
            1
          ],
          "my_array_field": [
            3,
            1,
            4,
            1,
            5,
            9,
            2,
            6,
            5
          ]
        },
        "_ingest": {
          "timestamp": "2024-05-30T22:10:13.405692128Z"
        }
      }
    }
  ]
}

步骤 3:摄取文档

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

POST testindex1/_doc?pipeline=sort-pipeline
{
  "my_array_field": [3, 1, 4, 1, 5, 9, 2, 6, 5]
}

响应

该请求将文档索引到 testindex1 索引中,然后将所有文档按 my_array_field 降序排序后索引,如以下响应所示

{
  "_index": "testindex1",
  "_id": "no-Py48BwFahnwl9KZzf",
  "_version": 1,
  "result": "created",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "_seq_no": 9,
  "_primary_term": 2
}

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

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

GET testindex1/_doc/no-Py48BwFahnwl9KZzf

剩余 350 字符

有问题?

想贡献?