This example is just a starter, small and limited example which shows a few tricks about symfony and elasticsearch. It lists existing indexes, gets single index, gets and adds/updates/deletes a document.


Mapping


Disabling listener prevents documents being updated after updating database. I disabled them just to show you how you can manually update a document.


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

IndexUtil


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.');
}
}
}

DocumentUtil


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;
}
}

Usage


$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, []);