Elasticsearch

hyperf/elasticsearch 主要为 elasticsearch-php 进行了客户端对象创建的工厂类封装,elasticsearch-php 默认使用 Guzzle Ring 客户端,在 hyperf/guzzle 中我们实现了协程版本的 Handler,所以可以直接使用 Hyperf\Elasticsearch\ClientBuilderFactory 创建一个新的 Builder

安装

  1. composer require hyperf/elasticsearch

使用

使用 ClientBuilderFactory 创建客户端

  1. <?php
  2. use Hyperf\Elasticsearch\ClientBuilderFactory;
  3. // 如果在协程环境下创建,则会自动使用协程版的 Handler,非协程环境下无改变
  4. $builder = $this->container->get(ClientBuilderFactory::class)->create();
  5. $client = $builder->setHosts(['http://127.0.0.1:9200'])->build();
  6. $info = $client->info();

自行创建客户端

  1. <?php
  2. use Elasticsearch\ClientBuilder;
  3. use Hyperf\Guzzle\RingPHP\PoolHandler;
  4. use Swoole\Coroutine;
  5. $builder = ClientBuilder::create();
  6. if (Coroutine::getCid() > 0) {
  7. $handler = make(PoolHandler::class, [
  8. 'option' => [
  9. 'max_connections' => 50,
  10. ],
  11. ]);
  12. $builder->setHandler($handler);
  13. }
  14. $client = $builder->setHosts(['http://127.0.0.1:9200'])->build();
  15. $info = $client->info();