排序处理器
2.16 版本引入
sort
处理器以升序或降序对项目数组进行排序。数字数组按数字排序,而字符串或混合数组(字符串和数字)按字典顺序排序。如果输入不是数组,则处理器会抛出错误。
请求正文字段
下表列出了所有可用的请求字段。
字段 | 数据类型 | 描述 |
---|---|---|
field | 字符串 | 要排序的字段。必须是数组。必需。 |
顺序 | 字符串 | 要应用的排序顺序。接受 asc 表示升序,desc 表示降序。默认为 asc 。 |
target_field | 字符串 | 存储排序后数组的字段名称。如果未指定,则排序后的数组存储在与原始数组(field 变量)相同的字段中。 |
tag | 字符串 | 处理器的标识符。 |
description | 字符串 | 处理器的描述。 |
ignore_failure | 布尔型 | 如果为 true ,则 OpenSearch 会忽略此处理器的任何失败 并继续运行搜索管道中的其余处理器。可选。默认为 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"
]
}
}
]
}
}