elasticsearch 3种分页方式

编辑于 2022-02-22 06:10:07 阅读 1559

本文将提供原始restfull apielasticsearch-php的示例

from + size

不适合深度分页,max_result_window默认10k

size, from类似sql语句里的limit, 如limit {from} {size};

  • size:每页条数
  • from:从第几个行开始,默认0

curl

curl -H "Content-Type: application/json" -XGET 'localhost:9200/article/_search?pretty' -d'
{
  "size": 2,
  "from": 0
}'

php

    public function search($from=0, $size=10) {
        $params = [
            'index' => 'article',
            'body' => [
                "sort"=>['_doc'],
                'from'=>$from,
                'size'=>$size,
            ]
        ];
        return $this->cache()->search($params);
    }

scroll

  • using [from] is not allowed in a scroll context;

curl

#首页
curl -H "Content-Type: application/json" -XGET 'localhost:9200/article/_search?pretty&scroll=1m' -d'
{
  "size": 2
}'
请求成功,结果里会有 _scroll_id 字段

#下一页
其中scroll_id的值是上一个请求中_scroll_id的值
注意:这次请求的接口和上一次的不一样

curl -H "Content-Type: application/json" -XGET 'localhost:9200/_search/scroll?pretty' -d'
{
  "scroll":"1m",
  "scroll_id":"FGluY2x1ZGVfY29udGV4dF91dWlkDXF1ZXJ5QW5kRmV0Y2gBFmNCWTM3c2U3Um5XYm1rS1FKU0xaVVEAAAAAAAAAYRZMX3BLM2FCOVFLaUhVbVk1STBnRTB3"
}'

php

    public function search($scroll='1m', $size=10) {
        $params = [
            'index' => 'article',
            "scroll" => $scroll,
            'body' => [
                "sort"=>['_doc'],
                'size'=>$size,
            ]
        ];
        return $this->cache()->search($params);
    }

    public function scroll($scroll_id, $scroll='1m') {
        return $this->cache()->scroll(['scroll_id'=>$scroll_id, 'scroll'=>$scroll]);
    }

search_after

使用search_after

  • 必须要设置from=0
  • 必须指定排序字段
  • search_after的值是上一个请求最后一条记录中某些字段的值,具体参考排序字段

curl

#首页
curl -H "Content-Type: application/json" -XGET 'localhost:9200/article/_search?pretty' -d'
{
  "size": 2,
  "from": 0,
  "sort": [
    {
      "_id": {
        "order": "desc"
      }
    }
  ]
}'
请求成功,结果里会有 sort 字段

#下一页
其中search_after的值是上一个请求最后一条记录中sort的值

curl -H "Content-Type: application/json" -XGET 'localhost:9200/article/_search?pretty' -d'
{
  "size": 2,
  "from": 0,
  "search_after": [7],
  "sort": [
    {
      "_id": {
        "order": "desc"
      }
    }
  ]
}'

php

    public function search($search_after = [], $size = 10) {
        $params = [
            'index' => 'article',
            'body' => [
                "sort" => ['_doc'],
                'from' => 0,
                'size' => $size,
            ]
        ];
        if (count($search_after) > 0) $params['body']['search_after'] = $search_after;
        return $this->cache()->search($params);
    }

参考

https://www.elastic.co/guide/cn/elasticsearch/php/current/index.html

广而告之,我的新作品《语音助手》上架Google Play了,欢迎下载体验