Installation Run:
composer require friendsofsymfony/elastica-bundle
Enable the bundle in AppKernel.php:
new FOS\ElasticaBundle\FOSElasticaBundle(),
Basic Configuration
Define a client in config/packages/fos_elastica.yaml (Symfony 4+) or config.yml (Symfony 2/3):
fos_elastica:
clients:
default: { host: localhost, port: 9200 }
First Use Case
Create a simple indexer for a Doctrine entity (e.g., Product):
# config/packages/fos_elastica.yaml
fos_elastica:
indexes:
product:
types:
product:
properties:
name: ~
price: ~
persistence:
driver: orm
model: App\Entity\Product
provider: ~
finder: ~
Run the indexer:
php bin/console fos:elastica:populate
Indexing Entities
persistence.driver: orm for Doctrine entities.properties (e.g., nested objects, dynamic fields).properties:
reviews:
type: nested
properties:
rating: ~
comment: ~
Querying Elasticsearch
Elastica client in services/controllers:
use FOS\ElasticaBundle\Finder\PaginatedFinderInterface;
class ProductSearchController
{
public function search(PaginatedFinderInterface $finder)
{
$results = $finder->find('product', [
'query' => [
'match' => ['name' => 'laptop']
]
]);
return $this->render('search.html.twig', ['results' => $results]);
}
}
Partial Indexing
fos:elastica:populate with --partial to update only changed entities:
php bin/console fos:elastica:populate --partial
Custom Indexers
FOS\ElasticaBundle\Indexer\AbstractIndexer for custom logic (e.g., pre-processing data before indexing).FOS\ElasticaBundle\Form\Type\ElasticaType for search-as-you-type fields.fos_elastica.index.populate or fos_elastica.index.delete events for side effects (e.g., logging).fos:elastica:populate via Symfony’s CronBundle or system cron.Version Mismatches
friendsofsymfony/elastica-bundle and ruflin/elastica versions align with your Symfony/Elasticsearch versions.Index Naming Collisions
product). Override with index_name:
indexes:
product_index: { ... }
Case Sensitivity in Mappings
keyword for exact matches:
properties:
sku: { type: keyword }
Partial Indexing Quirks
--partial skips entities not found in the database. Ensure your finder is correctly configured to avoid missing data.fos_elastica:
clients:
default:
host: localhost
port: 9200
debug: true # Logs raw Elasticsearch requests/responses
php bin/console fos:elastica:status
php bin/console cache:clear
php bin/console fos:elastica:clear
Custom Providers
FOS\ElasticaBundle\Provider\AbstractProvider for non-Doctrine data sources (e.g., API data).Dynamic Mappings
fos_elastica.index.create event to modify mappings dynamically:
// src/EventListener/ElasticaListener.php
public function onIndexCreate(IndexEvent $event)
{
$event->getIndex()->getMapping()->addType('product', [
'properties' => [
'dynamic_date' => ['type' => 'date']
]
]);
}
Aliases
fos_elastica.index.alias event for zero-downtime reindexing.Bulk Processing
FOS\ElasticaBundle\Indexer\AbstractIndexer::indexDocument() for custom bulk logic (e.g., batch inserts).How can I help you explore Laravel packages today?