排序处理器
sort 处理器用于对数组元素进行升序或降序排序。数值数组按数值大小排序,而字符串数组或混合类型数组(包含字符串和数字)则按字典顺序排序。如果输入不是数组,处理器将抛出错误。
请求体字段
下表列出了所有可用的请求字段。
| 字段 | 数据类型 | 描述 |
|---|---|---|
field |
字符串 | 待排序的字段。必须是数组类型。必需。 |
order |
字符串 | 应用的排序顺序。接受 asc(升序)或 desc(降序)。默认为 asc。 |
target_field |
字符串 | 用于存储排序后数组的字段名称。如果未指定,则排序后的数组将存储在与原始数组相同的字段中(即 field 变量)。 |
tag |
字符串 | 处理器的标识符。 |
description |
字符串 | 处理器的描述信息。 |
ignore_failure |
布尔值 | 如果设置为 true,UDB-SX 将忽略此处理器的任何失败,并继续运行搜索管道中的其余处理器。可选。默认值为 false。 |
示例
以下示例演示了如何使用包含 sort 处理器的搜索管道。
准备工作
创建一个名为 my_index 的索引,并为包含字符串数组字段 message 的文档建立索引:
POST /my_index/_doc/1
{
"message": ["one", "two", "three", "four"],
"visibility": "public"
}
创建搜索管道
创建一个搜索管道,其中包含一个 sort 响应处理器,该处理器会对 message 字段进行排序,并将排序后的结果存储在 sorted_message 字段中:
PUT /_search/pipeline/my_pipeline
{
"response_processors": [
{
"sort": {
"field": "message",
"target_field": "sorted_message"
}
}
]
}
使用搜索管道
在不使用搜索管道的情况下,搜索 my_index 中的文档:
GET /my_index/_search
响应中包含字段 message:
响应
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "my_index",
"_id": "1",
"_score": 1,
"_source": {
"message": [
"one",
"two",
"three",
"four"
],
"visibility": "public"
}
}
]
}
}
若要使用管道进行搜索,请在 search_pipeline 查询参数中指定管道名称:
GET /my_index/_search?search_pipeline=my_pipeline
sorted_message 字段包含了 message 字段中的字符串按字母顺序排序后的结果:
响应
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "my_index",
"_id": "1",
"_score": 1,
"_source": {
"visibility": "public",
"sorted_message": [
"four",
"one",
"three",
"two"
],
"message": [
"one",
"two",
"three",
"four"
]
}
}
]
}
}
您也可以使用 fields 选项来搜索文档中的特定字段:
POST /my_index/_search?pretty&search_pipeline=my_pipeline
{
"fields": ["visibility", "message"]
}
在响应中,message 字段经过排序,结果存储在 sorted_message 字段中:
响应
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "my_index",
"_id": "1",
"_score": 1,
"_source": {
"visibility": "public",
"sorted_message": [
"four",
"one",
"three",
"two"
],
"message": [
"one",
"two",
"three",
"four"
]
},
"fields": {
"visibility": [
"public"
],
"sorted_message": [
"four",
"one",
"three",
"two"
],
"message": [
"one",
"two",
"three",
"four"
]
}
}
]
}
}