該博文是集合幾個博客踩坑得來的,百度熱搜前幾篇都是缺胳膊少腿的,所以結合幾篇博客實現了一遍。
一、lumen使用Elasticsearch
首先需要搭建好的elasticsearch環境:
http://xxx.xxx.xxx:9200/
http://xxx.xxx.xxx:8200/
http://xxx.xxx.xxx:7200/
(1) lumen使用composer引入Elasticsearch插件
在lumen 的 composer.json 包依賴管理里加入如下插件。
"require": { "fadion/bouncy": "dev-l5" },
使用下面命令更新下載插件:
composer update "fadion/bouncy"
(2) 配置lumen文件
在bootstrap/app.php里面注冊新的服務(添加以下代碼,並注冊在AppServiceProvider之后。
$app->register(Fadion\Bouncy\BouncyServiceProvider::class);
把 "vendor/fadion/bouncy"
包中的config文件夾中的文件復制到自己的config
文件夾中,並把config.php
重命名為bouncy.php
,如圖所示:
在AppServiceProvider.php中加載搜索引擎配置:
protected function loadConfigFile() { $this->app->configure('elasticsearch'); }
改寫默認加載搜索引擎配置的函數(注意!在lumen框架缺少原來加載配置路徑函數,需要手動配置)並且使用引入:
$this->config_path('bouncy.php') $this->config_path('elasticsearch.php')
// 加載配置文件路徑函數 function config_path(){ return app()->basePath('config'); }
(3)配置elasticsearch.php文件配置連接的搜索引擎地址:
<?php return [ 'connectionClass' => '\Elasticsearch\Connections\GuzzleConnection', 'connectionFactoryClass' => '\Elasticsearch\Connections\ConnectionFactory', 'connectionPoolClass' => '\Elasticsearch\ConnectionPool\StaticNoPingConnectionPool', 'selectorClass' => '\Elasticsearch\ConnectionPool\Selectors\RoundRobinSelector', 'serializerClass' => '\Elasticsearch\Serializers\SmartSerializer', 'sniffOnStart' => false, 'connectionParams' => [], 'logging' => true, 'logObject' => null, 'logPath' => storage_path() . '/logs/elasticsearch.log', 'logLevel' => Monolog\Logger::WARNING, 'traceObject' => null, 'tracePath' => storage_path() . '/logs/elasticsearch_trace.log', 'traceLevel' => Monolog\Logger::WARNING, 'guzzleOptions' => [], 'connectionPoolParams' => [ 'randomizeHosts' => false ], 'retries' => null, 'hosts' => [ 'xxx.xxx.xxx.xx:7200', //添加Elasticsearch的地址,默認是127.0.0.1:9200 ] ];
(4) 修改model文件
在將要進行索引搜索的 Model 文件里,添加 BouncyTrait 的使用。 添加指定函數 documentFields
,設定要搜索出來的字段。
添加 BouncyTrait 的使用:
class AdvanceStudentModel extends BaseModel { use SoftDeletes; use BouncyTrait; // 使用ElasticSearch全文索引 protected $table = '庫名.表名'; protected $fillable = [ ]; protected $hidden = [ ]; protected $casts = [ ]; // 操作數據庫代碼 //...... /** * 在指定函數內 * 設置需要搜索出來的字段 * * @return array */ public function documentFields() { return [ 'id' => $this->id, 'class_id' => $this->class_id, 'student_name' => $this->student_name, 'achievement' => $this->achievement, 'accuracy_rate' => $this->accuracy_rate, ]; } }
(5) 使用
新建接口+寫好路由:
lass UserElasticSearch extends Controller { public function run() { $logic = new AdvanceStudentLogic(Auth::user()); $ret = $logic->searchParams(); return $this->renderRetData(Common::SUCCESS, 'success',$ret); } }
在logic文件中:
public function searchParams(){ //AdvanceStudentModel::all()->index(); // 全部設置為搜索索引。 $params = [ 'query' => [ 'match' => [ 'student_name' => 'qin' ] ], 'size' => 15 ]; $advanceStudentMode = new AdvanceStudentModel(); $data = $advanceStudentMode::search($params)->paginate(10)->toArray(); return $data; }
附上該插件原來github文檔地址: