-
Notifications
You must be signed in to change notification settings - Fork 733
/
Client.php
653 lines (553 loc) · 21 KB
/
Client.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
<?php
declare(strict_types=1);
namespace Elastica;
use Elastic\Elasticsearch\ClientInterface;
use Elastic\Elasticsearch\Exception\ClientResponseException;
use Elastic\Elasticsearch\Exception\HttpClientException;
use Elastic\Elasticsearch\Exception\MissingParameterException;
use Elastic\Elasticsearch\Exception\ServerResponseException;
use Elastic\Elasticsearch\Response\Elasticsearch;
use Elastic\Elasticsearch\Traits\ClientEndpointsTrait;
use Elastic\Elasticsearch\Traits\EndpointTrait;
use Elastic\Elasticsearch\Traits\NamespaceTrait;
use Elastic\Elasticsearch\Transport\Adapter\AdapterInterface;
use Elastic\Elasticsearch\Transport\Adapter\AdapterOptions;
use Elastic\Transport\Exception\NoAsyncClientException;
use Elastic\Transport\Exception\NoNodeAvailableException;
use Elastic\Transport\Transport;
use Elastic\Transport\TransportBuilder;
use Elastica\Bulk\Action;
use Elastica\Bulk\ResponseSet;
use Elastica\Exception\Bulk\ResponseException as BulkResponseException;
use Elastica\Exception\ClientException;
use Elastica\Exception\InvalidException;
use Elastica\Script\AbstractScript;
use Psr\Http\Client\ClientInterface as HttpClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* Client to connect the elasticsearch server.
*
* @author Nicolas Ruflin <spam@ruflin.com>
*/
class Client implements ClientInterface
{
use EndpointTrait;
use NamespaceTrait;
use ClientEndpointsTrait {
closePointInTime as protected elasticClientClosePointInTime;
bulk as protected elasticClientBulk;
}
private bool $elasticMetaHeader = true;
protected ClientConfiguration $_config;
protected ?RequestInterface $_lastRequest = null;
protected ?Elasticsearch $_lastResponse = null;
protected LoggerInterface $_logger;
protected ?string $_version = null;
private Transport $_transport;
public function __construct(string|array $config = [], ?LoggerInterface $logger = null)
{
$config = \is_string($config) ? ['hosts' => [$config]] : $config;
$this->_config = ClientConfiguration::fromArray($config);
$this->_logger = $logger ?? new NullLogger();
$this->_transport = $this->_buildTransport($this->getConfig());
}
public function getLogger(): LoggerInterface
{
return $this->_logger;
}
public function getTransport(): Transport
{
return $this->_transport;
}
public function setAsync(bool $async): self
{
throw new \Exception('Not supported');
}
public function getAsync(): bool
{
throw new \Exception('Not supported');
}
public function setElasticMetaHeader(bool $active): self
{
$this->elasticMetaHeader = $active;
return $this;
}
public function getElasticMetaHeader(): bool
{
return $this->elasticMetaHeader;
}
public function setResponseException(bool $active): self
{
throw new \Exception('Not supported');
}
public function getResponseException(): bool
{
throw new \Exception('Not supported');
}
/**
* Get current version.
*
* @throws NoNodeAvailableException if all the hosts are offline
* @throws ClientResponseException if the status code of response is 4xx
* @throws ServerResponseException if the status code of response is 5xx
* @throws ClientException
*/
public function getVersion(): string
{
if ($this->_version) {
return $this->_version;
}
$data = $this->info()->asArray();
return $this->_version = $data['version']['number'];
}
/**
* Sets specific config values (updates and keeps default values).
*
* @param array $config Params
*/
public function setConfig(array $config): self
{
foreach ($config as $key => $value) {
$this->_config->set($key, $value);
}
return $this;
}
/**
* Returns a specific config key or the whole config array if not set.
*
* @throws InvalidException if the given key is not found in the configuration
*
* @return array|bool|string
*/
public function getConfig(string $key = '')
{
return $this->_config->get($key);
}
/**
* Sets / overwrites a specific config value.
*
* @param mixed $value Value
*/
public function setConfigValue(string $key, $value): self
{
return $this->setConfig([$key => $value]);
}
/**
* @param array|string $keys config key or path of config keys
* @param mixed $default default value will be returned if key was not found
*/
public function getConfigValue($keys, $default = null)
{
$value = $this->_config->getAll();
foreach ((array) $keys as $key) {
if (isset($value[$key])) {
$value = $value[$key];
} else {
return $default;
}
}
return $value;
}
/**
* Returns the index for the given connection.
*/
public function getIndex(string $name): Index
{
return new Index($this, $name);
}
/**
* Uses _bulk to send documents to the server.
*
* Array of \Elastica\Document as input. Index has to be set inside the
* document, because for bulk settings documents, documents can belong to
* any index
*
* @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
*
* @param array|Document[] $docs Array of Elastica\Document
*
* @throws InvalidException If docs is empty
* @throws MissingParameterException if a required parameter is missing
* @throws NoNodeAvailableException if all the hosts are offline
* @throws ClientResponseException if the status code of response is 4xx
* @throws ServerResponseException if the status code of response is 5xx
* @throws BulkResponseException
* @throws ClientException
*/
public function updateDocuments(array $docs, array $requestParams = []): ResponseSet
{
if (!$docs) {
throw new InvalidException('Array has to consist of at least one element');
}
$bulk = new Bulk($this);
$bulk->addDocuments($docs, Action::OP_TYPE_UPDATE);
foreach ($requestParams as $key => $value) {
$bulk->setRequestParam($key, $value);
}
return $bulk->send();
}
/**
* Uses _bulk to send documents to the server.
*
* Array of \Elastica\Document as input. Index has to be set inside the
* document, because for bulk settings documents, documents can belong to
* any index
*
* @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
*
* @param array|Document[] $docs Array of Elastica\Document
*
* @throws InvalidException If docs is empty
* @throws MissingParameterException if a required parameter is missing
* @throws NoNodeAvailableException if all the hosts are offline
* @throws ClientResponseException if the status code of response is 4xx
* @throws ServerResponseException if the status code of response is 5xx
* @throws BulkResponseException
* @throws ClientException
*/
public function addDocuments(array $docs, array $requestParams = []): ResponseSet
{
if (!$docs) {
throw new InvalidException('Array has to consist of at least one element');
}
$bulk = new Bulk($this);
$bulk->addDocuments($docs);
foreach ($requestParams as $key => $value) {
$bulk->setRequestParam($key, $value);
}
return $bulk->send();
}
/**
* Update document, using update script. Requires elasticsearch >= 0.19.0.
*
* @param int|string $id document id
* @param AbstractScript|array|Document $data raw data for request body
* @param string $index index to update
* @param array $options array of query params to use for query. For possible options check es api
*
* @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html
*
* @throws MissingParameterException if a required parameter is missing
* @throws NoNodeAvailableException if all the hosts are offline
* @throws ClientResponseException if the status code of response is 4xx
* @throws ServerResponseException if the status code of response is 5xx
* @throws ClientException
*/
public function updateDocument($id, $data, $index, array $options = []): Response
{
$params = [
'id' => $id,
'index' => $index,
];
if ($data instanceof AbstractScript) {
$requestData = $data->toArray();
} elseif ($data instanceof Document) {
$requestData = ['doc' => $data->getData()];
if ($data->getDocAsUpsert()) {
$requestData['doc_as_upsert'] = true;
}
$docOptions = $data->getOptions(
[
'consistency',
'parent',
'percolate',
'refresh',
'replication',
'retry_on_conflict',
'routing',
'timeout',
]
);
$options += $docOptions;
} else {
$requestData = $data;
}
// If an upsert document exists
if ($data instanceof AbstractScript || $data instanceof Document) {
if ($data->hasUpsert()) {
$requestData['upsert'] = $data->getUpsert()->getData();
}
}
$params['body'] = $requestData;
$response = $this->update(\array_merge($params, $options));
if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300
&& $data instanceof Document
&& ($data->isAutoPopulate() || $this->getConfigValue(['document', 'autoPopulate'], false))
) {
$data->setVersionParams($response->asArray());
}
return $this->toElasticaResponse($response);
}
/**
* Bulk deletes documents.
*
* @param array|Document[] $docs
*
* @throws InvalidException
* @throws MissingParameterException if a required parameter is missing
* @throws NoNodeAvailableException if all the hosts are offline
* @throws ClientResponseException if the status code of response is 4xx
* @throws ServerResponseException if the status code of response is 5xx
* @throws BulkResponseException
* @throws ClientException
*/
public function deleteDocuments(array $docs, array $requestParams = []): ResponseSet
{
if (!$docs) {
throw new InvalidException('Array has to consist of at least one element');
}
$bulk = new Bulk($this);
$bulk->addDocuments($docs, Action::OP_TYPE_DELETE);
foreach ($requestParams as $key => $value) {
$bulk->setRequestParam($key, $value);
}
return $bulk->send();
}
/**
* Returns the status object for all indices.
*/
public function getStatus(): Status
{
return new Status($this);
}
/**
* Returns the current cluster.
*/
public function getCluster(): Cluster
{
return new Cluster($this);
}
/**
* Deletes documents with the given ids, index, type from the index.
*
* @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
*
* @param array $ids Document ids
* @param Index|string $index Index name
* @param bool|string $routing Optional routing key for all ids
*
* @throws InvalidException
* @throws MissingParameterException if a required parameter is missing
* @throws NoNodeAvailableException if all the hosts are offline
* @throws ClientResponseException if the status code of response is 4xx
* @throws ServerResponseException if the status code of response is 5xx
* @throws BulkResponseException
* @throws ClientException
*/
public function deleteIds(array $ids, $index, $routing = false): ResponseSet
{
if (!$ids) {
throw new InvalidException('Array has to consist of at least one id');
}
$bulk = new Bulk($this);
$bulk->setIndex($index);
foreach ($ids as $id) {
$action = new Action(Action::OP_TYPE_DELETE);
$action->setId($id);
if (!empty($routing)) {
$action->setRouting($routing);
}
$bulk->addAction($action);
}
return $bulk->send();
}
/**
* Bulk operation.
*
* Every entry in the params array has to exactly on array
* of the bulk operation. An example param array would be:
*
* array(
* array('index' => array('_index' => 'test', '_id' => '1')),
* array('field1' => 'value1'),
* array('delete' => array('_index' => 'test', '_id' => '2')),
* array('create' => array('_index' => 'test', '_id' => '3')),
* array('field1' => 'value3'),
* array('update' => array('_id' => '1', '_index' => 'test')),
* array('doc' => array('field2' => 'value2')),
* );
*
* @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
*
* @throws InvalidException
* @throws MissingParameterException if a required parameter is missing
* @throws NoNodeAvailableException if all the hosts are offline
* @throws ClientResponseException if the status code of response is 4xx
* @throws ServerResponseException if the status code of response is 5xx
* @throws BulkResponseException
* @throws ClientException
*/
public function bulk(array $params): ResponseSet
{
if (!$params) {
throw new InvalidException('Array has to consist of at least one param');
}
$bulk = new Bulk($this);
$bulk->addRawData($params);
return $bulk->send();
}
public function baseBulk(array $params): Response
{
return $this->toElasticaResponse($this->elasticClientBulk($params));
}
public function sendRequest(RequestInterface $request): Elasticsearch
{
$this->_lastRequest = $request;
$this->_lastResponse = null;
try {
$response = $this->_transport->sendRequest($request);
$result = new Elasticsearch();
$result->setResponse($response, 'HEAD' !== $request->getMethod());
$this->_lastResponse = $result;
} catch (ServerResponseException|NoNodeAvailableException $e) {
$this->_logger->error('Elastica Request Failure', [
'exception' => $e,
'request' => $request,
'request_content' => \json_decode($request->getBody()->__toString(), true),
]);
throw $e;
}
$this->_logger->debug('Elastica Request', [
'request' => \json_decode($request->getBody()->__toString(), true),
'response' => 'HEAD' !== $request->getMethod() ? $result->asArray() : $result->asString(),
'responseStatus' => $response->getStatusCode(),
]);
return $result;
}
/**
* Force merges all search indices.
*
* @see https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-forcemerge.html
*
* @throws NoNodeAvailableException if all the hosts are offline
* @throws ClientResponseException if the status code of response is 4xx
* @throws ServerResponseException if the status code of response is 5xx
* @throws ClientException
*/
public function forcemergeAll(array $args = []): Response
{
return $this->toElasticaResponse($this->indices()->forcemerge($args));
}
/**
* Closes the given PointInTime.
*
* @see https://www.elastic.co/guide/en/elasticsearch/reference/current/point-in-time-api.html#close-point-in-time-api
*
* @throws NoNodeAvailableException if all the hosts are offline
* @throws ClientResponseException if the status code of response is 4xx
* @throws ServerResponseException if the status code of response is 5xx
* @throws ClientException
*/
public function closePointInTime(string $pointInTimeId): Response
{
return $this->toElasticaResponse($this->elasticClientClosePointInTime(['body' => ['id' => $pointInTimeId]]));
}
/**
* Refreshes all search indices.
*
* @see https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-refresh.html
*
* @throws NoNodeAvailableException if all the hosts are offline
* @throws ClientResponseException if the status code of response is 4xx
* @throws ServerResponseException if the status code of response is 5xx
* @throws ClientException
*/
public function refreshAll(): Response
{
return $this->toElasticaResponse($this->indices()->refresh());
}
public function getLastRequest(): ?RequestInterface
{
return $this->_lastRequest;
}
public function getLastResponse(): ?Elasticsearch
{
return $this->_lastResponse;
}
public function toElasticaResponse(Elasticsearch|ResponseInterface $elasticsearchResponse): Response
{
return ResponseConverter::toElastica($elasticsearchResponse);
}
protected function _buildTransport(array $config): Transport
{
$hosts = isset($config['hosts']) && \is_array($config['hosts']) ? $config['hosts'] : [ClientConfiguration::DEFAULT_HOST];
$transportConfig = $config['transport_config'] ?? [];
$builder = TransportBuilder::create();
$builder->setHosts($hosts);
$builder->setLogger($this->_logger);
// Http client
if (isset($transportConfig['http_client'])) {
$builder->setClient($transportConfig['http_client']);
}
// Set HTTP client options
$builder->setClient(
$this->setTransportClientOptions(
$builder->getClient(),
$transportConfig['http_client_config'] ?? [],
$transportConfig['http_client_options'] ?? []
)
);
// Cloud id
if (isset($config['cloud_id'])) {
$builder->setCloudId($config['cloud_id']);
}
// Node Pool
if (isset($transportConfig['node_pool'])) {
$builder->setNodePool($transportConfig['node_pool']);
}
$transport = $builder->build();
// The default retries is equal to the number of hosts
if (isset($config['retries']) && (int) $config['retries'] > 0) {
$transport->setRetries($config['retries']);
} else {
$transport->setRetries(\count($hosts));
}
// Basic authentication
if (isset($config['username'], $config['password'])) {
$transport->setUserInfo($config['username'], $config['password']);
}
// API key
if (!empty($config['api_key'])) {
if (!empty($config['username'])) {
throw new InvalidException('You cannot use APIKey and Basic Authentication together.');
}
$transport->setHeader('Authorization', \sprintf('ApiKey %s', $config['api_key']));
}
/*
* Elastic cloud optimized with gzip
* @see https://github.com/elastic/elasticsearch-php/issues/1241 omit for Symfony HTTP Client
*/
if (isset($config['cloud_id']) && !$this->isSymfonyHttpClient($transport)) {
$transport->setHeader('Accept-Encoding', 'gzip');
}
return $transport;
}
/**
* Returns true if the transport HTTP client is Symfony.
*/
protected function isSymfonyHttpClient(Transport $transport): bool
{
if (\str_contains($transport->getClient()::class, 'Symfony\Component\HttpClient')) {
return true;
}
try {
return \str_contains($transport->getAsyncClient()::class, 'Symfony\Component\HttpClient');
} catch (NoAsyncClientException $e) {
return false;
}
}
protected function setTransportClientOptions(HttpClientInterface $client, array $config, array $clientOptions = []): HttpClientInterface
{
if (empty($config) && empty($clientOptions)) {
return $client;
}
$adapterClass = AdapterOptions::HTTP_ADAPTERS[$client::class] ?? throw new HttpClientException(\sprintf('The HTTP client %s is not supported for custom options', $client::class));
if (!\class_exists($adapterClass) || !\in_array(AdapterInterface::class, \class_implements($adapterClass), true)) {
throw new HttpClientException(\sprintf('The class %s does not exists or does not implement %s', $adapterClass, AdapterInterface::class));
}
return (new $adapterClass())->setConfig($client, $config, $clientOptions);
}
}