Elasticsearch的SearchAfter

时间:2022-12-09 18:12:00

Elasticsearch使用Search After深度分页,分页的方式是上一页的最后一条数据sort里面的值来确定下一页的位置,在分页请求的过程中,有索引数据的增删,会实时的反映到游标上。每一页的数据依赖于上一页最后一条数据,所以不能跳页请求;

使用search_after必须要设置from=0;

最后一条数据里拿到sort属性的值传入到search_after;

curl 第一次请求:

index/type/_search?pretty -d
{
"size": 10,
"query": {
"match": {
"age": "男"
}
},
"sort": [{
"_uid": {
"order": "desc"
}
}]
}

返回:

{
"took": 28,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 286,
"max_score": null,
"hits": [{
"_index": "user_member",
"_type": "member_itu",
"_id": "123465",
"_score": null,
"_source": {
"userId": "123456",
"name": "123",
"updateTime": "2022-12-09 13:05"
},
"sort": [
"123465"
]
}]
}
}


curl 分页第二次请求:

index/type/_search?pretty -d
{
"size": 10,
"search_after": ["123456"],
"query": {
"match": {
"age": "男"
}
},
"sort": [{
"_uid": {
"order": "desc"
}
}]
}

分页返回:

{
"took": 28,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 286,
"max_score": null,
"hits": [{
"_index": "user_member",
"_type": "member_itu",
"_id": "123457",
"_score": null,
"_source": {
"userId": "123457",
"name": "124",
"updateTime": "2022-12-09 14:05"
},
"sort": [
"123457"
]
}]
}
}