laravel使用Elasticsearch

一、composer安装elasticsearch扩展包

composer require elasticsearch/elasticsearch “7.12.x” --ignore-platform-reqs

二、配置es

  • config/database.php
 'elasticsearch' => [
        'hosts' => explode(',',env('ES_HOSTS')),
    ]
  • .env
 ES_HOSTS=192.168.148.188:9200 #默认9200,端口可不写

三、初始化 Elasticsearch 对象,并注入到 Laravel 容器中

在laravel容器中自定义一个名为es的服务对象,通过ESClientBuilder以及配置文件中的信息连接到es,我们可以通过app(‘es’)->info()查看连接之后的es对象信息。

  • App/Providers/AppServiceProvider.php
<?php

namespace App\Providers;

use Elasticsearch\ClientBuilder as ElasticClientBuilder;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        // 注册一个名为 es 的单例
        $this->app->singleton('es',function (){
            // 从配置文件读取 Elasticsearch 服务器列表
            $builder =  ElasticClientBuilder ::create()->setHosts(config('database.elasticsearch.hosts'));
            // 如果是开发环境
            if (app()->environment()==='local'){
                // 配置日志,Elasticsearch 的请求和返回数据将打印到日志文件中,方便我们调试
                $builder->setLogger(app('log')->driver());
            }
            return $builder->build();
        });
    }

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

四、测试

  1. php artisan tinker
    Laravel artisan 的 tinker 是一个 REPL (read-eval-print-loop),REPL 是指 交互式命令行界面,它可以让你输入一段代码去执行,并把执行结果直接打印到命令行界面里。
  2. app(‘es’)->info()
we123@LAPTOP-P1SSGT9F MINGW64 /e/project/lmrs/lmrs
$ php artisan tinker
Psy Shell v0.10.8 (PHP 7.3.4 — cli) by Justin Hileman

>>> app('es')->info()
=> [
     "name" => "es-node-1",
     "cluster_name" => "my-application",
     "cluster_uuid" => "UFOIRUHPRZuVVRNaSeubJw",
     "version" => [
       "number" => "7.12.1",
       "build_flavor" => "default",
       "build_type" => "docker",
       "build_hash" => "3186837139b9c6b6d23c3200870651f10d3343b7",
       "build_date" => "2021-04-20T20:56:39.040728659Z",
       "build_snapshot" => false,
       "lucene_version" => "8.8.0",
       "minimum_wire_compatibility_version" => "6.8.0",
       "minimum_index_compatibility_version" => "6.0.0-beta1",
     ],
     "tagline" => "You Know, for Search",
   ]
>>>

快速检查es集群的健康状况

GET /_cat/health?v
laravel使用Elasticsearch

如何快速了解集群的健康状况?status -> green、yellow、red?

  • green:每个索引的primary shard和replica shard都是active状态的
  • yellow:每个索引的primary shard都是active状态的,但是部分replica shard不是active状态,处于不可用的状态
  • red:不是所有索引的primary shard都是active状态的,部分索引有数据丢失了

快速查看es集群中有哪些索引

GET /_cat/indices?v
laravel使用Elasticsearch

上一篇:【Elasticsearch】实用BM25 -第1部分: shard 如何影响Elasticsearch中的相关性评分


下一篇:数据库 shard 分片