问题描述:elasticsearch from和size分页查询得不到想要的结果
代码:
#分页
#from就相当于MySQL中limit后面的第一个参数
#from就相当于MySQL中limit后面的第二个参数
GET /my_index/_search
{
"query": {
"match_all": {}
},
"from": 1,
"size": 2
}
出错结果:
#①当 from为0时
{
"took" : 14,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 4,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "my_index",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"id" : 1,
"title" : "华为笔记本电脑",
"category" : "华为",
"images" : "http://www.gulixueyuan.com/xm.jpg",
"price" : 5388
}
},
{
"_index" : "my_index",
"_type" : "_doc",
"_id" : "2",
"_score" : 1.0,
"_source" : {
"id" : 2,
"title" : "华为手机",
"category" : "华为",
"images" : "http://www.gulixueyuan.com/xm.jpg",
"price" : 5500
}
}
]
}
}
②当from为1时
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 4,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "my_index",
"_type" : "_doc",
"_id" : "2",
"_score" : 1.0,
"_source" : {
"id" : 2,
"title" : "华为手机",
"category" : "华为",
"images" : "http://www.gulixueyuan.com/xm.jpg",
"price" : 5500
}
},
{
"_index" : "my_index",
"_type" : "_doc",
"_id" : "3",
"_score" : 1.0,
"_source" : {
"id" : 3,
"title" : "VIVO手机",
"category" : "vivo",
"images" : "http://www.gulixueyuan.com/xm.jpg",
"price" : 3600
}
}
]
}
}
问题描述: 当显示每页显示数量为2时,让from=0,再让from=1,数据出现了重叠
“Devil组”引证GPT后的撰写:
例如,下面是一个使用 search_after 参数的查询示例:
GET /my_index/_search
{
"query": {
"match_all": {}
},
"size": 2,
"sort": [
{"_id": "asc"}
],
"search_after": [2]
}
用 _id 字段进行排序,并将文档 id 为 2 作为 search_after 参数的值。这将从文档 id 为 3 开始返回两个文档。每个新的分页查询都使用前一页的最后一个文档的排序值作为 search_after 参数的值,以确保不会出现重叠的结果。
有啥问题,from理解成skip的意思正常行为就是跳过1条从第二条开始返回两条记录
加一个排序字段吧