laravel Es搜尋 檢索高亮顯示

QQ糖的音符發表於2022-03-13
**安裝教程,網上都可以查詢到。這裡只簡單文字介紹,詳細步驟可私信我**
1.下載安裝JDK
下載地址https://www.oracle.com/technetwork/java/javase/downloads/index.html
2.配置 JAVA_HOME環境變數
3.開啟命令列視窗,輸入java -version檢視JDK版本 出現版本號 安裝成功
4.下載安裝elasticsearch
下載地址https://www.elastic.co/downloads
5.配置Path環境變數
*6.開啟命令列視窗 執行命令 elasticsearch -d 啟動elasticsearch*
7.瀏覽器開啟 http://localhost:9200 出現詳細資訊 安裝成功
8.安裝Elasticsearch-Head
elasticsearch-head是一個用於瀏覽ElasticSearch叢集並與其進行互動的Web專案
GitHub託管地址:https://github.com/mobz/elasticsearch-head下載並解壓:
9.使用cnpm安裝,這樣速度會快一些 cnpm的安裝方法:
npm install -g cnpm --registry=https://registry.npm.taobao.org
*10.npm run start  啟動成功後,可通過http://localhost:9100進行訪問*
11.由於跨域(Elasticsearch位於9200埠),需要新增配置: E:\elasticsearch-7.1.0\config\elasticsearch.yml中

#新新增的配置行
http.cors.enabled: true
http.cors.allow-origin: "*"

1.首先我們要先連線Es

<?php

namespace App\Http\Controllers;

use App\Models\Article;
use Elasticsearch\ClientBuilder;

class Text extends Controller
{
    //受保護的:只能自己和自己的子類呼叫
    protected $es;

    //建構函式的作用:例項化類的時候自動呼叫,執行每個方法前都會自動執行一次
    public function __construct()
    {
        //連線es
        $this->es = ClientBuilder::create()->setHosts(['localhost:9200'])->build();
    }

    //建立索引(類似於建立資料庫)
    public function createIndex(){
        //設定引數
        //index表示索引名稱,類似於資料庫名稱
        $params = [
            'index'=>'zg4',
            'body'=>[
                'mappings'=>[
                    'properties'=>[//彙總欄位的
                        'title'=>[
                            'type'=>'text',
                            "analyzer" => "ik_max_word",
                            "search_analyzer" => "ik_max_word"
                        ]
                    ]
                ]
            ]
        ];
        $this->es->indices()->create($params);
    }


    //新增文件(給資料庫的某張資料表新增資料)
    public function addDoc(){
        $params = [
            'index'=>'zg3',//類似於資料庫名稱
            'type'=>'article',//類似於資料表名稱(不需要建立的,直接指定就可以了)
            'id'=>1,//當前要新增的資料的主鍵id(自己指定的)
            'body'=>['id'=>1,'name'=>'zhangsan','sex'=>1]//資料
        ];
        $res = $this->es->index($params);
        dump($res);
    }

    //修改文件(給資料庫的某張表修改資料)
    public function updateDoc(){
        $params = [
            'index'=>'zg3',
            'type'=>'article',
            'id'=>1,
            'body'=>[
                //修改的內容
                'doc'=>['name'=>'張三']
            ]
        ];

        $res = $this->es->update($params);
        dump($res);
    }

    //刪除文件(根據id刪除某個資料庫下的某張表下的內容)
    public function deleteDoc(){
        try {
            $params = [
                'index'=>'zg3',
                'type'=>'article',
                'id'=>1
            ];
            $this->es->delete($params);
            return json(['code'=>0,'msg'=>'刪除成功']);
        }catch (\Exception $e){
            return json(['code'=>1,'msg'=>'刪除失敗']);
        }
    }

    //批量新增文件
    public function addDocAll(){
        $data = Article::select();
        $data = collection($data)->toArray();
        foreach ($data as $k=>$v){
            $params = [
                'index'=>'zg4',//類似於資料庫名稱
                'type'=>'_doc',//類似於資料表名稱(不需要建立的,直接指定就可以了)
                'id'=>$v['id'],//當前要新增的資料的主鍵id(自己指定的)
                'body'=>$v//資料
            ];
            $res = $this->es->index($params);
        }
    }

    //es搜尋
    public function esSearch(Request $request)
    {
        $word = $request->get('keyName');
        if (empty($word)) {
            $data = Housing::with(['HouOtt', 'HouPay', 'HouSet', 'HouType'])->get()->toArray();
            return response()->json(['code' => 1, 'msg' => 'word引數不能為空', 'data' => $data]);
        }
        $page = $request->get('page', 1);//接收當前頁,預設值是1
        $size = config('pagesize');//每頁顯示條數
        $from = ($page - 1) * $size;//偏移量
        $params = [
            'index' => 'index',
            'body' => [
                //執行
                'query' => [
                    //匹配
                    'match' => [
                        'f_name' => $word
                    ]
                ],
                'highlight' => [
                    'pre_tags' => ["<span style='color: red'>"],
                    'post_tags' => ['</span>'],
                    'fields' => [
                        'f_name' => new \stdClass()
                    ]
                ]
            ],
            'size' => $size,//每頁顯示的條數
            'from' => $from//偏移量
        ];
        $res = $this->es->search($params);
        $data = $res['hits']['hits'];
        foreach ($data as $k => $v) {
            $data[$k]['_source']['f_name'] = $v['highlight']['f_name'][0];
        }
        $data = array_column($data, '_source');
        return response()->json(['code' => 0, 'msg' => '成功', 'data' => $data]);
    }
}

——-更新——
框架安裝:composer require elasticsearch/elasticsearch
elasticsearch -d 啟動elasticsearch/bin/elasticsearch.bat 9200
命令列 切換到head 執行npm run start

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Elasticsearch\ClientBuilder;

//use Illuminate\Http\Request;

class EsController extends Controller
{
    //私有的靜態屬性
    private static $EsClient = false;

    //私有的構造方法
    private function __construct()
    {

    }

    //3.私有的克隆方法
    private function __clone()
    {

    }

    //公有的靜態方法
    public static function getIntance()
    {
        if (self::$EsClient == false) {
            self::$EsClient = ClientBuilder::create()->build();
        }
        return self::$EsClient;
    }

    public function escreate()
    {
        $params = [
            'index' => 'gao1103s'//庫名
        ];
        // Create the index
        $client = ClientBuilder::create()->build();
        $response = $client->indices()->create($params);
        //指定分詞
        $client = ClientBuilder::create()->build();
        $params = [
            'index' => 'gao1103s',
            'body' => [
                'settings' => [
                    'number_of_shards' => 3,
                    'number_of_replicas' => 2
                ],
                'mappings' => [
                    '_source' => [
                        'enabled' => true
                    ],
                    'properties' => [
                        'name' => [
                            'type' => 'text',
                            "analyzer" => "ik_max_word",
                            "search_analyzer" => "ik_max_word"
                        ],
                        'desc' => [
                            'type' => 'text',
                            "analyzer" => "ik_max_word",
                            "search_analyzer" => "ik_max_word"
                        ]
                    ]
                ]
            ]
        ];
        // Create the index with mappings and settings now
        $response = $client->indices()->create($params);
    }

    public function addition()
    {
        $client = ClientBuilder::create()->build();
        $data = WechatShop::all();
        $body = [];
        foreach ($data as $v) {
            $params['body'][] = array(
                'index' => array(
                    '_index' => "gao1103s",
                    '_type' => 'text'
                ),
            );

            $params['body'][] = array(
                'id' => $v['id'],
                'shop_name' => $v['shop_name'],
                'shop_img' => $v['shop_img'],
                'shop_price' => $v['shop_price'],
            );
        }
        $response = $client->bulk($params);
        print_r($response);
    }

    public function essearch(Request $request)
    {
        $search_field = "shop_name";//搜尋的欄位
        $word = $request->input('word', '');//接收關鍵字
        $page = $request->input('page', 1);//接收當前頁(如果沒接收到,預設是1)
        $size = $request->input('size', 5);;//每頁顯示條數
        $limit = ($page - 1) * $size;//偏移量
        $client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();//建立es例項
        //設定查詢的條件
        if (empty($word)) {
            $body = [

            ];
        } else {
            $body = [
                //查詢內容
                'query' => [
                    'match' => [//匹配
                        $search_field => $word//匹配欄位
                    ]
                ],
                'highlight' => [//高亮
                    'pre_tags' => ["<em style='color: red'>"],//樣式自己寫
                    'post_tags' => ["</em>"],
                    'fields' => [
                        $search_field => new \stdClass()
                    ]
                ]
            ];
        }
        $params = [
            'index' => 'gao1103s',//索引(類似於庫)
            'body' => $body,
            'size' => $size,//每頁顯示條數
            'from' => $limit//偏移量
        ];
        $results = $client->search($params);//es搜尋
        if (!empty($word)) {
            foreach ($results['hits']['hits'] as $k => $v) {
                $results['hits']['hits'][$k]['_source'][$search_field] = $v['highlight'][$search_field][0];
            }
        }


        $data = array_column($results['hits']['hits'], '_source');
        $arr['page'] = $page;//當前頁
        $arr['total'] = $results['hits']['total']['value'];//總條數
        $arr['last_page'] = ceil($results['hits']['total']['value'] / $size);//總頁數
        $arr['data'] = $data;//資料
        return response()->json($arr);
    }

}

小程式頁面不解析

<rich-text nodes="{{item.f_name}}"></rich-text>
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章