babenkoivan/elastic-client

Laravel 集成的官方 PHP Elasticsearch 客户端

v3.0.0 2024-06-18 06:53 UTC

This package is auto-updated.

Last update: 2024-09-18 07:15:47 UTC


README

Latest Stable Version Total Downloads License Tests Code style Static analysis Donate PayPal

Support the project!

官方 PHP Elasticsearch 客户端,集成于 Laravel。

内容

兼容性

当前版本的 Elastic Client 已经与以下配置进行了测试

  • PHP 8.2
  • Elasticsearch 8.x
  • Laravel 11.x

如果你的项目使用较旧的 Laravel(或 PHP)版本,请检查此包的先前主要版本

安装

可以通过 Composer 安装此库

composer require babenkoivan/elastic-client

配置

要更改客户端设置,您需要首先发布配置文件

php artisan vendor:publish --provider="Elastic\Client\ServiceProvider"

在新建的 config/elastic.client.php 文件中,您可以定义默认连接名称并使用配置散列描述多个连接。您可以在这里了解更多关于从配置散列构建客户端的信息这里

return [
    'default' => env('ELASTIC_CONNECTION', 'default'),
    'connections' => [
        'default' => [
            'hosts' => [
                env('ELASTIC_HOST', 'localhost:9200'),
            ],
            // configure basic authentication
            'basicAuthentication' => [
                env('ELASTIC_USERNAME'),
                env('ELASTIC_PASSWORD'),
            ],
            // configure HTTP client (Guzzle by default)
            'httpClientOptions' => [
                'timeout' => 2,
            ],
        ],
    ],
];

如果您需要更多控制客户端创建,您可以创建自己的客户端构建器

use Elastic\Elasticsearch\ClientInterface;
use Elastic\Client\ClientBuilderInterface;

class MyClientBuilder implements ClientBuilderInterface
{
    public function default(): ClientInterface
    {
        // should return a client instance for the default connection 
    }
    
    public function connection(string $name): ClientInterface
    {
        // should return a client instance for the connection with the given name 
    }
}

不要忘记在您的应用程序服务提供者中注册构建器

class MyAppServiceProvider extends Illuminate\Support\ServiceProvider
{
    public function register()
    {
        $this->app->singleton(ClientBuilderInterface::class, MyClientBuilder::class);
    }
}

用法

使用 Elastic\Client\ClientBuilderInterface 获取对客户端实例的访问

namespace App\Console\Commands;

use Elastic\Elasticsearch\ClientInterface;
use Elastic\Client\ClientBuilderInterface;
use Illuminate\Console\Command;

class CreateIndex extends Command
{
    protected $signature = 'create:index {name}';

    protected $description = 'Creates an index';

    public function handle(ClientBuilderInterface $clientBuilder)
    {
        // get a client for the default connection
        $client = $clientBuilder->default();
        // get a client for the connection with name "write"
        $client = $clientBuilder->connection('write');
    
        $client->indices()->create([
            'index' => $this->argument('name')
        ]);
    }
}