天天看点

laravel如何使用使用elasticsearch

1、composer安装elasticsearch扩展包

composer require elasticsearch/elasticsearch "7.12.x" --ignore-platform-reqs
           
laravel如何使用使用elasticsearch

2、配置es

     config/database.php

'elasticsearch'=>[
            'hosts' => explode(',',env('ES_HOSTS')),
        ]
           

配置.env

ES_HOSTS=192.168.84.3
           

3、初始化elasticsearch对象

注入到容器中 App/Providers/AppServiceProvider.php

<?php
    namespace App\Providers;
    use Illuminate\Support\ServiceProvider;
    use Elasticsearch\ClientBuilder as ESClientBuilder;
    class AppServiceProvider extends ServiceProvider{
        /**
         * Register any application services.
         *
         * @return void
         */
        public function register(){
            $this->app->singleton('es',function(){
                $bulider = ESClientBuilder::create()->setHosts(config('database.elasticsearch.hosts'));
                if(app()->environment()==='local'){
                    $bulider->setLogger(app('log')->driver());
                }
                return $bulider->build();
            });

        }

        /**
         * Bootstrap any application services.
         *
         * @return void
         */
        public function boot()
        {
            //
        }
    }
           

4、测试

php artisan tinker 

>>>app('es')->info()
           
laravel如何使用使用elasticsearch

出现以上界面说明安装成功了

如果出现 Elasticsearch\Common\Exceptions\NoNodesAvailableException with message 'No alive nodes found in your cluster'

最好确认下ES是否开启,或者ES配置是否正确。

下一篇写 Elasticsearch+kibana及分词相关介绍。