haridarshan/opensearch-client

官方 PHP OpenSearch 客户端,与 Laravel 集成

v1.0.1 2024-03-27 06:43 UTC

This package is auto-updated.

Last update: 2024-09-27 08:41:29 UTC


README

官方 PHP OpenSearch 客户端,与 Laravel 集成。

内容

兼容性

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

  • PHP 7.4-8.x
  • OpenSearch 2.x
  • Laravel 6.x-10.x

安装

可以通过 Composer 安装库

composer require haridarshan/opensearch-client

配置

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

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

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

return [
    'default' => env('OPENSEARCH_CONNECTION', 'default'),
    'connections' => [
        'default' => [
            'hosts' => [
                env('OPENSEARCH_HOST', 'localhost:9200'),
            ],
            // configure basic authentication
            'basicAuthentication' => [
                env('OPENSEARCH_USERNAME'),
                env('OPENSEARCH_PASSWORD'),
            ],
            'retries' => (int) env('OPENSEARCH_RETRIES', 2),
            // disable SSL Verification
            'sslVerification' => env('OPENSEARCH_SSL_VERIFICATION', false),
            // configure HTTP client (Guzzle by default)
            'httpClientOptions' => [
                'timeout' => 2,
            ],
        ],
    ],
];

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

// see OpenSearch\Laravel\Client\ClientBuilder for the reference
class MyClientBuilder implements OpenSearch\Laravel\Client\ClientBuilderInterface
{
    public function default(): Client
    {
        // should return a client instance for the default connection 
    }
    
    public function connection(string $name): Client
    {
        // 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);
    }
}

使用

使用 OpenSearch\Laravel\Client\ClientBuilderInterface 获取客户端实例的访问权限

namespace App\Console\Commands;

use OpenSearch\Client;
use OpenSearch\Laravel\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')
        ]);
    }
}