babenkoivan/elastic-client

The official PHP Elasticsearch client integrated with Laravel

v1.2.0 2021-02-16 07:28 UTC

This package is auto-updated.

Last update: 2021-07-24 10:24:37 UTC


README

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

Buy Me A Coffee

The official PHP Elasticsearch client integrated with Laravel.

Contents

Compatibility

The current version of Elastic Client has been tested with the following configuration:

  • PHP 7.2-8.0
  • Elasticsearch 7.x

Installation

The library can be installed via Composer:

composer require babenkoivan/elastic-client

Configuration

To change the client settings you need to publish the configuration file first:

php artisan vendor:publish --provider="ElasticClient\ServiceProvider"

Then you can adjust the configuration hash in config/elastic.client.php file. Note, that you can provide any settings supported by \Elasticsearch\ClientBuilder::fromConfig():

return [
    'hosts' => [
        env('ELASTIC_HOST', 'localhost:9200'),
    ]
];

If you want to connect to AWS Elasticsearch, you can configure a handler, which would sign requests with AWS credentials. For example, you can install renoki-co/aws-elastic-client package and reconfigure Elastic Client in AppServiceProvider::register() as follows:

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(\Elasticsearch\Client::class, static function () {
            $config = config('elastic.client');

            $config['handler'] = new \RenokiCo\AwsElasticHandler\AwsHandler([
                'enabled' => env('AWS_ELASTICSEARCH_ENABLED', false),
                'aws_access_key_id' => env('AWS_ACCESS_KEY_ID'),
                'aws_secret_access_key' => env('AWS_SECRET_ACCESS_KEY'),
                'aws_region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
                'aws_session_token' => env('AWS_SESSION_TOKEN'), // optional
            ]);

            return \Elasticsearch\ClientBuilder::fromConfig($config);
        });
    }
}

Usage

Type hint \Elasticsearch\Client or use resolve function to retrieve the client instance in your code:

namespace App\Console\Commands;

use Elasticsearch\Client;
use Illuminate\Console\Command;

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

    protected $description = 'Creates an index';

    public function handle(Client $client)
    {
        $client->indices()->create([
            'index' => $this->argument('name')
        ]);
    }
}