详解Laravel8 ES封装及其使用方法

本篇文章给大家介绍有关laravel8的相关知识,内容包括讲解laravel8 es封装以及使用方法,希望对大家有所帮助!

详解Laravel8 ES封装及其使用方法

【相关推荐:laravel视频教程

composer 安装

composer require elasticsearch/elasticsearch

ES 封装

<?php namespace AppEs; use ElasticsearchClientBuilder; class MyEs {     //ES客户端链接     private $client;     /**      * 构造函数      * MyElasticsearch constructor.      */     public function __construct()     {         $this->client = ClientBuilder::create()-&gt;setHosts(['127.0.0.1:9200'])-&gt;build();     }     /**      * 判断索引是否存在      * @param string $index_name      * @return bool|mixed|string      */     public function exists_index($index_name = 'test_ik')     {         $params = [             'index' =&gt; $index_name         ];         try {             return $this-&gt;client-&gt;indices()-&gt;exists($params);         } catch (ElasticsearchCommonExceptionsBadRequest400Exception $e) {             $msg = $e-&gt;getMessage();             $msg = json_decode($msg,true);             return $msg;         }     }     /**      * 创建索引      * @param string $index_name      * @return array|mixed|string      */     public function create_index($index_name = 'test_ik') { // 只能创建一次         $params = [             'index' =&gt; $index_name,             'body' =&gt; [                 'settings' =&gt; [                     'number_of_shards' =&gt; 5,                     'number_of_replicas' =&gt; 1                 ]             ]         ];         try {             return $this-&gt;client-&gt;indices()-&gt;create($params);         } catch (ElasticsearchCommonExceptionsBadRequest400Exception $e) {             $msg = $e-&gt;getMessage();             $msg = json_decode($msg,true);             return $msg;         }     }     /**      * 删除索引      * @param string $index_name      * @return array      */     public function delete_index($index_name = 'test_ik') {         $params = ['index' =&gt; $index_name];         $response = $this-&gt;client-&gt;indices()-&gt;delete($params);         return $response;     }     /**      * 添加文档      * @param $id      * @param $doc ['id'=&gt;100, 'title'=&gt;'phone']      * @param string $index_name      * @param string $type_name      * @return array      */     public function add_doc($id,$doc,$index_name = 'test_ik',$type_name = 'goods') {         $params = [             'index' =&gt; $index_name,             'type' =&gt; $type_name,             'id' =&gt; $id,             'body' =&gt; $doc         ];         $response = $this-&gt;client-&gt;index($params);         return $response;     }     /**      * 判断文档存在      * @param int $id      * @param string $index_name      * @param string $type_name      * @return array|bool      */     public function exists_doc($id = 1,$index_name = 'test_ik',$type_name = 'goods') {         $params = [             'index' =&gt; $index_name,             'type' =&gt; $type_name,             'id' =&gt; $id         ];         $response = $this-&gt;client-&gt;exists($params);         return $response;     }     /**      * 获取文档      * @param int $id      * @param string $index_name      * @param string $type_name      * @return array      */     public function get_doc($id = 1,$index_name = 'test_ik',$type_name = 'goods') {         $params = [             'index' =&gt; $index_name,             'type' =&gt; $type_name,             'id' =&gt; $id         ];         $response = $this-&gt;client-&gt;get($params);         return $response;     }     /**      * 更新文档      * @param int $id      * @param string $index_name      * @param string $type_name      * @param array $body ['doc' =&gt; ['title' =&gt; '苹果手机iPhoneX']]      * @return array      */     public function update_doc($id = 1,$index_name = 'test_ik',$type_name = 'goods', $body=[]) {         // 可以灵活添加新字段,最好不要乱添加         $params = [             'index' =&gt; $index_name,             'type' =&gt; $type_name,             'id' =&gt; $id,             'body' =&gt; $body         ];         $response = $this-&gt;client-&gt;update($params);         return $response;     }     /**      * 删除文档      * @param int $id      * @param string $index_name      * @param string $type_name      * @return array      */     public function delete_doc($id = 1,$index_name = 'test_ik',$type_name = 'goods') {         $params = [             'index' =&gt; $index_name,             'type' =&gt; $type_name,             'id' =&gt; $id         ];         $response = $this-&gt;client-&gt;delete($params);         return $response;     }     /**      * 搜索文档 (分页,排序,权重,过滤)      * @param string $index_name      * @param string $type_name      * @param array $body      * $body = [                 'query' =&gt; [                     'match' =&gt; [                         'fang_name' =&gt; [                             'query' =&gt; $fangName                         ]                     ]                 ],                 'highlight'=&gt;[                     'fields'=&gt;[                         'fang_name'=&gt;[                             'pre_tags'=&gt;[                                 '<span>'                             ],                             'post_tags'=&gt;[                                 '</span>'                             ]                         ]                     ]                 ]             ];      * @return array      */     public function search_doc($index_name = "test_ik",$type_name = "goods",$body=[]) {         $params = [             'index' =&gt; $index_name,             'type' =&gt; $type_name,             'body' =&gt; $body         ];         $results = $this-&gt;client-&gt;search($params);         return $results;     } }

将数据表中所有数据添加至 ES

public function esAdd()     {         $data = Good::get()-&gt;toArray();         $es = new MyEs();         if (!$es-&gt;exists_index('goods')) {             //创建es索引,es的索引相当于MySQL的数据库             $es-&gt;create_index('goods');         }         foreach ($data as $model) {             $es-&gt;add_doc($model['id'], $model, 'goods', '_doc');         }     }

每在 MySQL 里添加一条数据,在 es 里也添加一条

直接将代码补在 MySQL 添加入库的逻辑方法里即可

        //添加至MySQL         $res=Good::insertGetId($arr);         $es = new MyEs();         if (!$es-&gt;exists_index('goods')) {             $es-&gt;create_index('goods');         }         //添加至es         $es-&gt;add_doc($res, $arr, 'goods', '_doc');         return $res;

进行 MySQL 数据修改时,也更新 es 的数据

直接将代码补在 MySQL 修改数据的逻辑方法里即可

      //修改MySQL的数据         $res=Good::where('id',$id)-&gt;update($arr);         $es = new MyEs();         if (!$es-&gt;exists_index('goods')) {             $es-&gt;create_index('goods');         }         //修改es的数据         $es-&gt;update_doc($id, 'goods', '_doc',['doc'=&gt;$arr]);         return $res;

通过 ES 实现搜索功能

public function search()     {         //获取搜索值         $search = request()-&gt;get('search');         if (!empty($search)) {             $es = new MyEs();             $body = [                 'query' =&gt; [                     'match' =&gt; [                         'title' =&gt; [                             'query' =&gt; $search                         ]                     ]                 ],                 'highlight'=&gt;[                     'fields'=&gt;[                         'title'=&gt;[                             'pre_tags'=&gt;[                                 '<span>'                             ],                             'post_tags'=&gt;[                                 '</span>'                             ]                         ]                     ]                 ]             ];             $res = $es-&gt;search_doc('goods', '_doc', $body);             $data = array_column($res['hits']['hits'], '_source');             foreach ($data as $key=&gt;&amp;$v){                  $v['title'] = $res['hits']['hits'][$key]['highlight']['title'][0];             }             unset($v);             return $data;         }         $data = Good::get();         return $data;     }

另,补充 es 分页搜索

如果是在微信小程序中使用的话,运用上拉触底事件即可

此功能是在上面搜索功能之上添加代码实现的

1. 接收前台小程序传递来的当前页

2. 调用 es 封装类的搜索方法时,多传两个参数

3. 在 es 封装类的搜索方法中增加两个形参

搜索后搜索值高亮显示

如果是在微信小程序中使用的话,是直接将标签和值一起输出到页面的,加入解析富文本的标签可以将标签转化格式,达到高亮效果

<rich-text></rich-text>

原文作者:amateur转自链接:https://learnku.com/articles/66177

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享