<?php
namespace App\Extern;
use Elastica\Client;
use Elastica\Exception\NotFoundException;
use Elastica\Index;
use Elastica\Search;
use Psr\Log\LoggerInterface;
use RuntimeException;
class ExternElasticService
{
protected $client;
protected $search;
/** @var Index $index */
protected $index;
/** @var LoggerInterface $logger */
private $logger;
public function __construct($host, $port, $transport, LoggerInterface $logger)
{
$this->logger = $logger;
$this->client = new Client(
[
'servers' => [
[
'host' => $host,
'port' => $port,
'transport' => $transport
]
],
]
);
$this->search = new Search($this->client);
}
public function getCount()
{
return $this->search->count();
}
public function getClient()
{
return $this->client;
}
public function getSearch()
{
return $this->search;
}
public function getIndex()
{
return $this->index;
}
public function addAndSetIndex(string $index)
{
try {
$this->search->addIndex($index);
$this->index = $this->client->getIndex($index);
} catch (RuntimeException $exception) {
$this->logger->alert(
"impossible to add index " . $index . ": " . $exception->getMessage(),
['exception' => $exception]
);
}
}
public function getDocument($id)
{
$doc = null;
try {
$doc = $this->index->getDocument($id)->getData();
$doc["_id"] = $id;
} catch (NotFoundException $exception) {
$doc = null;
} catch (RuntimeException $exception) {
$this->logger->alert(
"impossible to get document: " . $exception->getMessage(),
['exception' => $exception]
);
}
return $doc;
}
public function updateDocument($id, $data)
{
$upd = null;
try {
$doc = $this->index->getDocument($id);
$doc->setData(array_merge($doc->getData(), (array)json_decode($data)));
$upd = $this->index->updateDocument($doc);
} catch (RuntimeException $exception) {
$this->logger->alert(
"impossible to update document: " . $exception->getMessage(),
['exception' => $exception]
);
$upd = null;
}
return $upd;
}
public function addDocument($id, $data)
{
try {
$doc = $this->index->createDocument($id, $data);
return $this->index->addDocument($doc);
} catch (RuntimeException $exception) {
$this->logger->alert(
"impossible to delete document: " . $exception->getMessage(),
['exception' => $exception]
);
}
return null;
}
public function deleteDocument($id)
{
$del = null;
try {
$doc = $this->index->getDocument($id);
$del = $this->index->deleteDocument($doc);
} catch (NotFoundException $exception) {
$del = null;
} catch (RuntimeException $exception) {
$this->logger->alert(
"impossible to delete document: " . $exception->getMessage(),
['exception' => $exception]
);
}
return $del;
}
}