分页

from and size

GET /user/_search
{
  "from":0,
  "size":10,
  "query":{
    "term":{
      "user":"王五"
    }
  }
}

      注意:搜索请求耗用的堆内存和时间与 from + size 大小成正比。分页越深耗用越大,为了不因分页导致OOM或严重影响性能,ES中规定from + size 不能大于索引setting参数 index.max_result_window 的值,默认值为 10,000

    对于深度分页,es推荐使用 scroll 接口,scroll接口不适合用在实时搜索的场景里。search_after 提供了一个活的游标来拉取从上次返回的最后一个请求开始拉取下一页的数据。

  使用Scroll api进行高效深度滚动,但滚动上下文代价很高,建议不要将其用于实时用户请求。该search_after参数通过提供实时游标来解决此问题。

GET twitter/_search
{
    "query": {
        "match": {
            "title": "elasticsearch"
        }
    },
    "sort": [
        {"date": "asc"},
        {"tie_breaker_id": "asc"}      
    ]
}

  响应:

{
  "took" : 17,
  "timed_out" : false,
  "_shards" : ...,
  "hits" : {
    "total" : ...,
    "max_score" : null,
    "hits" : [
      ...
      {
        "_index" : "twitter",
        "_id" : "654322",
        "_score" : null,
        "_source" : ...,
        "sort" : [
          1463538855,
          "654322"
        ]
      },
      {
        "_index" : "twitter",
        "_id" : "654323",
        "_score" : null,
        "_source" : ...,
        "sort" : [                                
          1463538857,
          "654323"
        ]
      }
    ]
  }
}

  每个文档具有一个唯一值的字段应该用作排序规范的仲裁器。否则,具有相同排序值的文档的排序顺序将是未定义的。建议的方法是使用字段_id,它肯定包含每个文档的一个唯一值。

       使用最后的一个文档的sort排序值,将它传递给 search_after 参数:

GET twitter/_search
{
    "query": {
        "match": {
            "title": "elasticsearch"
        }
    },
    "search_after": [1463538857, "654323"],
    "sort": [
        {"date": "asc"},
        {"tie_breaker_id": "asc"}
    ]
}

  search_after不是自由跳转到随机页面而是并行滚动多个查询的解决方案。

posted on 2022-11-12 19:50  溪水静幽  阅读(72)  评论(0)    收藏  举报