1. 程式人生 > 其它 >tp5.0 實現 ElasticSearch 的搜尋

tp5.0 實現 ElasticSearch 的搜尋

1.前端搜尋框

<form action="{:url('home/goods/index')}" method="get">
    <div>
        <input type="text" id="autocomplete" name="keywords" value="{$Request.param.keywords}" />
        <button type="submit">搜尋</button>
    </div>
</form>

2.在後端接值 判斷 搜尋

public function
index($id=0) { //接收引數 $keywords = input('keywords'); if(empty($keywords)){ //獲取指定分類下商品列表 if(!preg_match('/^\d+$/', $id)){ $this->error('引數錯誤'); } //查詢分類下的商品 $list = \app\common\model\Goods::where('cate_id', $id
)->order('id desc')->paginate(10); //查詢分類名稱 $category_info = \app\common\model\Category::find($id); $cate_name = $category_info['cate_name']; }else{ try{ //從ES中搜索 $list = \app\home\logic\GoodsLogic::search();
$cate_name = $keywords; }catch (\Exception $e){ $this->error('伺服器異常'); } } return view('index', ['list' => $list, 'cate_name' => $cate_name]); }

3. 邏輯部分 在\app\home\logic\GoodsLogic.php 中

<?php

namespace app\home\logic;

use think\Controller;

class GoodsLogic extends Controller
{
    public static function search(){
        //例項化ES工具類
        $es = new \tools\es\MyElasticsearch();
        //計算分頁條件
        $keywords = input('keywords');
        $page = input('page', 1);
        $page = $page < 1 ? 1 : $page;
        $size = 10;
        $from = ($page - 1) * $size;
        //組裝搜尋引數體
        $body = [
            'query' => [
                'bool' => [
                    'should' => [
                        [ 'match' => [ 'cate_name' => [
                            'query' => $keywords,
                            'boost' => 4, // 權重大
                        ]]],
                        [ 'match' => [ 'goods_name' => [
                            'query' => $keywords,
                            'boost' => 3,
                        ]]],
                        [ 'match' => [ 'goods_desc' => [
                            'query' => $keywords,
                            'boost' => 2,
                        ]]],
                    ],
                ],
            ],
            'sort' => ['id'=>['order'=>'desc']],
            'from' => $from,
            'size' => $size
        ];
        //進行搜尋
        $results = $es->search_doc('goods_index', 'goods_type', $body);
        //獲取資料
        $data = array_column($results['hits']['hits'], '_source');
        $total = $results['hits']['total']['value'];
        //分頁處理
        $list = \tools\es\EsPage::paginate($data, $size, $total);
        return $list;
    }
}

4.在封裝一個es分頁的方法 在\tools\es\EsPage.php 中

<?php
namespace tools\es;

use think\Config;

class 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);
    }
}