23/02/2018 - ELASTICSEARCH, SYMFONY
Bu symfony ve elasticsearch ile ilgili başlangıç amaçlı küçük ve sınırlı bir örnektir. Bir veya birden fazla indexleri verir. Bununlar birlikte döküman ekler, yeniler veya siler.
Ayarlardan listener
iptal edildiğinde, veritabanında yapılan işlemler indexe yansıtılmaz. Bunu yapmamın nedeni, gerekli işlemi kendimiz yapacağız.
fos_elastica:
clients:
default: { host: 127.0.0.1, port: 9200 }
indexes:
country:
client: default
use_alias: true
index_name: country_%kernel.environment%
types:
country:
properties:
id:
type: integer
name:
type: text
abbreviation:
type: text
leagues:
type: object
properties:
id:
type: integer
name:
type: text
founded:
type: integer
persistence:
driver: orm
model: AppBundle\Entity\Country
finder: ~
provider: ~
listener:
insert: false
update: false
delete: false
declare(strict_types=1);
namespace AppBundle\Util\Elastica;
use AppBundle\Exception\ElasticaException;
use FOS\ElasticaBundle\Elastica\Index;
use FOS\ElasticaBundle\Index\IndexManager;
use InvalidArgumentException;
class IndexUtil
{
private $manager;
public function __construct(IndexManager $manager)
{
$this->manager = $manager;
}
public function getOne(string $name): Index
{
return $this->find($name);
}
public function getAll(): iterable
{
return $this->manager->getAllIndexes();
}
public function getAliasName(string $name): string
{
return $this->find($name)->getName();
}
private function find(string $name): Index
{
try {
return $this->manager->getIndex($name);
} catch (InvalidArgumentException $e) {
throw new ElasticaException('Index not found.');
}
}
}
declare(strict_types=1);
namespace AppBundle\Util\Elastica;
use AppBundle\Exception\ElasticaException;
use Elastica\Document;
use Elastica\Query\Terms;
use FOS\ElasticaBundle\Elastica\Index;
class DocumentUtil
{
public function getOne(Index $index, int $id): iterable
{
$terms = new Terms();
$terms->setTerms('id', [$id]);
return $index->search($terms)->getDocuments();
}
public function updateOne(Index $index, int $id, iterable $data): void
{
$terms = new Terms();
$terms->setTerms('id', [$id]);
$result = $index->search($terms);
if ($result->count() !== 1) {
throw new ElasticaException('Document not found.');
}
/** @var Document $document */
$document = $result->getDocuments()[0];
$document->setData($this->createData($document->getData(), $data));
// $index->addDocuments([$document]);
// $index->updateDocuments([$document]);
// $index->deleteDocuments([$document]);
}
private function createData(iterable $oldData, iterable $newData): iterable
{
$oldData['name'] = 'Updated - Old name:'.$oldData['name'];
return $oldData + $newData;
}
}
$indexes = $this->indexUtil->getAll();
$index = $this->indexUtil->getOne('country');
$alias = $this->indexUtil->getAliasName('country');
$document = $this->documentUtil->getOne($index, 1);
$updatedDocument = $this->documentUtil->updateOne($index, 4, []);