Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Elastica Bundle Laravel Package

birdoffice/elastica-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require friendsofsymfony/elastica-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        FriendsOfSymfony\ElasticaBundle\FOSElasticaBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration Configure Elasticsearch client in config/packages/fos_elastica.yaml:

    fos_elastica:
        clients:
            default: { host: '%env(ELASTICSEARCH_HOST)%', port: '%env(ELASTICSEARCH_PORT)%' }
        indexes:
            app:
                client: default
                settings:
                    number_of_shards: 3
                    number_of_replicas: 0
                types:
                    product:
                        properties:
                            name: ~
                            price: ~
    
  3. First Use Case: Indexing a Doctrine Entity Annotate your entity (e.g., Product):

    use FriendsOfSymfony\ElasticaBundle\Annotation as Elastica;
    
    /**
     * @Elastica\Document(repositoryClass="App\Repository\ProductElasticaRepository")
     */
    class Product {}
    

    Define a repository:

    namespace App\Repository;
    
    use FriendsOfSymfony\ElasticaBundle\Repository;
    
    class ProductElasticaRepository extends Repository {}
    

    Index data via CLI:

    php bin/console fos:elastica:populate
    

Implementation Patterns

Workflows

  1. Automatic Indexing with Doctrine Events Leverage listeners for postPersist, postUpdate, and postRemove:

    # config/packages/fos_elastica.yaml
    fos_elastica:
        listeners:
            product:
                type: App\Entity\Product
                events:
                    - onFlush
                    - onClear
    
  2. Manual Indexing Use the repository to index/unindex entities:

    $product = $entityManager->find(Product::class, 1);
    $repository->index($product); // Index
    $repository->remove($product); // Unindex
    
  3. Querying Elasticsearch

    $query = $repository->createQuery()
        ->select('p')
        ->where('p.name', 'partial', 'search_term')
        ->setLimit(10);
    
    $results = $repository->find($query);
    
  4. Dynamic Mapping Skip configuration and rely on Elasticsearch’s dynamic mapping:

    fos_elastica:
        indexes:
            app:
                types:
                    dynamic_product: ~ # No properties defined
    

Integration Tips

  • Symfony Serializer: Use fos_elastica.serializer to customize serialization:
    fos_elastica:
        serializer:
            groups: ['default', 'elasticsearch']
    
  • Custom Mappings: Override default mappings via YAML or PHP:
    fos_elastica:
        indexes:
            app:
                types:
                    product:
                        properties:
                            slug: { type: keyword }
    
  • Bulk Operations: Use fos:elastica:populate for large datasets:
    php bin/console fos:elastica:populate --batch-size=100
    

Gotchas and Tips

Pitfalls

  1. Doctrine vs. Elasticsearch Data Mismatch

    • Ensure entity properties match Elasticsearch mappings. Use @Elastica\Property to override:
      /**
       * @Elastica\Property(type="integer")
       */
      private $price;
      
    • Debug mappings with:
      php bin/console fos:elastica:info
      
  2. Listener Overhead

    • Automatic listeners trigger on every Doctrine flush. For large datasets, disable listeners and index manually:
      fos_elastica:
          listeners:
              product: { events: [] } # Disable listeners
      
  3. Index Naming Conflicts

    • Default index names are app_<entity>. Customize via:
      fos_elastica:
          indexes:
              app:
                  alias: { app_products: product }
      
  4. Serialization Issues

    • Circular references or non-serializable objects break indexing. Use @Groups or @Exclude:
      use JMS\Serializer\Annotation as Serializer;
      
      /**
       * @Serializer\Exclude()
       */
      private $sensitiveData;
      

Debugging

  • Check Index Status:
    php bin/console fos:elastica:info
    
  • Log Queries: Enable debug mode in config/packages/dev/fos_elastica.yaml:
    fos_elastica:
        debug: true
    
  • Test Locally: Use Dockerized Elasticsearch (e.g., docker.elastic.co/elasticsearch/elasticsearch:7.15.0).

Extension Points

  1. Custom Indexers Extend FOSElasticaBundle\Indexer\IndexerInterface for custom logic:

    class CustomIndexer implements IndexerInterface {
        public function index($document, $indexName, $typeName) { ... }
    }
    

    Register in services:

    services:
        App\Indexer\CustomIndexer:
            tags: [fos_elastica.indexer]
    
  2. Event Subscribers Listen to fos_elastica.index or fos_elastica.remove events:

    use FriendsOfSymfony\ElasticaBundle\Event\IndexEvent;
    
    class MySubscriber implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [IndexEvent::INDEX => 'onIndex'];
        }
    
        public function onIndex(IndexEvent $event) { ... }
    }
    
  3. Custom Query Builders Extend FOSElasticaBundle\Query\QueryBuilder for domain-specific queries:

    class ProductQueryBuilder extends QueryBuilder {
        public function filterByCategory($category) { ... }
    }
    

    Bind to repository:

    class ProductElasticaRepository extends Repository {
        protected function createQueryBuilder() {
            return new ProductQueryBuilder($this);
        }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware