主题
分页与排序
在搜索结果中,合理的分页与排序能显著提升数据展示的效率和用户体验。Elasticsearch 提供多种方式灵活实现分页和排序。
1. 分页实现
通过 from
和 size
参数控制返回结果的起始位置和数量。
示例
json
GET /my-index/_search
{
"from": 0,
"size": 10,
"query": {
"match_all": {}
}
}
from
:跳过结果数量,默认0size
:返回结果数量,默认10,最大限制可配置
2. 排序实现
使用 sort
参数指定排序字段和顺序。
示例:按价格升序排序
json
GET /my-index/_search
{
"query": {
"match_all": {}
},
"sort": [
{ "price": "asc" }
]
}
多字段排序
json
GET /my-index/_search
{
"query": {
"match_all": {}
},
"sort": [
{ "category": "asc" },
{ "price": "desc" }
]
}
3. 注意事项
- 大量深度分页(高
from
值)会影响性能,推荐使用search_after
进行深度分页 - 排序字段应是可排序的字段类型,如
keyword
、数值或日期 - 默认排序按相关度评分(_score)降序
通过合理设置分页和排序参数,可以灵活控制结果展示,满足多样化业务需求。