TP5 ElasticSearch 封装分页类 并 实现搜索后分页

1、在第三方扩展类库中封装EsPage.php类文件

2、声明命名空间

namespace tools\es;

use think\Config;

3、封装EsPage类

public static function paginate($results, $listRows = null, $simple = false, $config = [])
    {
        if (is_int($simple)) {
            $total  = $simple;
            $simple = false;
        }else{
            $total = null;
            $simple = true;
        }

        if (is_array($listRows)) {
            $config   = array_merge(Config::get('paginate'), $listRows);
            $listRows = $config['list_rows'];
        } else {
            $config   = array_merge(Config::get('paginate'), $config);
            $listRows = $listRows ?: $config['list_rows'];
        }

        /** @var Paginator $class */
        $class = false !== strpos($config['type'], '\\') ? $config['type'] : '\\think\\paginator\\driver\\' . ucwords($config['type']);
        $page  = isset($config['page']) ? (int) $config['page'] : call_user_func([
            $class,
            'getCurrentPage',
        ], $config['var_page']);

        $page = $page < 1 ? 1 : $page;

        $config['path'] = isset($config['path']) ? $config['path'] : call_user_func([$class, 'getCurrentPath']);

        return $class::make($results, $listRows, $page, $total, $simple, $config);
    }

4、进行搜索并分页

try{
       //接收参数
       $keywords = input('keywords');
       $page = input('page',1);
       $size = 10;
       $limit = ($page-1)*$size;
       $client = ClientBuilder::create()->build();
       $params = [
           'index' => 'goods',
            //'type' => '_doc',
            'body' => [
            'query' => [
                  'match' => [
                     'goods_name' => $keywords
                   ]
            ],
            'highlight' => [
                  'pre_tags' => ["<span style='color: red'>"],
                  'post_tags' => ["</span>"],
                  'fields' => [
                     "goods_name" => new \stdClass()
                  ]
                 ]
                ]
          ];
                $params["size"] = $size;
                $params["from"] = $limit;
                $results = $client->search($params);
                foreach ($results['hits']['hits'] as $k => $v){
                    $results['hits']['hits'][$k]['_source']['goods_name'] = $v['highlight']['goods_name'][0];
                }
                $data = array_column($results['hits']['hits'], '_source');
                $total = $results['hits']['total']['value'];
                //分页处理
                $list = \tools\es\EsPage::paginate($data, $size, $total);
                $cate_name = $keywords;
}catch (\Exception $e){
      $this->error('服务器异常');
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值