lumen框架使用Elasticsearch详解

 

该博文是集合几个博客踩坑得来的,百度热搜前几篇都是缺胳膊少腿的,所以结合几篇博客实现了一遍。

一、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文档地址:

https://github.com/fadion/Bouncy

posted @ 2018-11-19 13:57  QinXiao.Shou  阅读(1684)  评论(0编辑  收藏  举报