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('服务器异常');
}