2019-04-05 10:01:15 +08:00
|
|
|
|
# Elasticsearch
|
|
|
|
|
|
2019-12-12 16:24:04 +08:00
|
|
|
|
[hyperf/elasticsearch](https://github.com/hyperf/elasticsearch) 主要為 [elasticsearch-php](https://github.com/elastic/elasticsearch-php) 進行了客户端對象創建的工廠類封裝,[elasticsearch-php](https://github.com/elastic/elasticsearch-php) 默認使用 `Guzzle Ring` 客户端,在 [hyperf/guzzle](https://github.com/hyperf/guzzle) 中我們實現了協程版本的 `Handler`,所以可以直接使用 `Hyperf\Elasticsearch\ClientBuilderFactory` 創建一個新的 `Builder`。
|
2019-04-22 12:32:20 +08:00
|
|
|
|
|
2019-12-12 16:24:04 +08:00
|
|
|
|
## 安裝
|
2019-04-22 12:35:01 +08:00
|
|
|
|
|
|
|
|
|
```bash
|
|
|
|
|
composer require hyperf/elasticsearch
|
|
|
|
|
```
|
2019-04-22 12:32:20 +08:00
|
|
|
|
## 使用
|
|
|
|
|
|
2019-12-12 16:24:04 +08:00
|
|
|
|
### 使用 `ClientBuilderFactory` 創建客户端
|
2019-06-02 00:37:13 +08:00
|
|
|
|
|
2019-04-22 12:32:20 +08:00
|
|
|
|
```php
|
|
|
|
|
<?php
|
|
|
|
|
|
2019-04-27 13:03:37 +08:00
|
|
|
|
use Hyperf\Elasticsearch\ClientBuilderFactory;
|
|
|
|
|
|
2019-12-12 16:24:04 +08:00
|
|
|
|
// 如果在協程環境下創建,則會自動使用協程版的 Handler,非協程環境下無改變
|
2019-06-02 00:37:13 +08:00
|
|
|
|
$builder = $this->container->get(ClientBuilderFactory::class)->create();
|
2019-04-22 12:32:20 +08:00
|
|
|
|
|
2019-06-02 00:37:13 +08:00
|
|
|
|
$client = $builder->setHosts(['http://127.0.0.1:9200'])->build();
|
2019-04-22 12:32:20 +08:00
|
|
|
|
|
2019-06-02 00:37:13 +08:00
|
|
|
|
$info = $client->info();
|
2019-04-22 12:32:20 +08:00
|
|
|
|
```
|
2019-07-29 16:50:40 +08:00
|
|
|
|
|
2019-12-12 16:24:04 +08:00
|
|
|
|
### 自行創建客户端
|
2019-07-29 16:50:40 +08:00
|
|
|
|
|
|
|
|
|
```php
|
|
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
use Elasticsearch\ClientBuilder;
|
|
|
|
|
use Hyperf\Guzzle\RingPHP\PoolHandler;
|
|
|
|
|
use Swoole\Coroutine;
|
|
|
|
|
|
|
|
|
|
$builder = ClientBuilder::create();
|
|
|
|
|
if (Coroutine::getCid() > 0) {
|
|
|
|
|
$handler = make(PoolHandler::class, [
|
|
|
|
|
'option' => [
|
|
|
|
|
'max_connections' => 50,
|
|
|
|
|
],
|
|
|
|
|
]);
|
|
|
|
|
$builder->setHandler($handler);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$client = $builder->setHosts(['http://127.0.0.1:9200'])->build();
|
|
|
|
|
|
|
|
|
|
$info = $client->info();
|
|
|
|
|
```
|
|
|
|
|
|
2021-04-26 08:25:52 +08:00
|
|
|
|
### 如何設置用户名密碼
|
|
|
|
|
|
|
|
|
|
當搜索引擎需要使用用户名和密碼時,比如購買了 `Elasticsearch` 企業版,我們可以使用以下 `host` 訪問搜索引擎。
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
http://username:password@xxxx.aliyuncs.com:9200
|
|
|
|
|
```
|