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

friendsofsymfony/elastica-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require friendsofsymfony/elastica-bundle
    

    For Symfony Flex, use the recipe.

  2. Configure Elasticsearch Connection (config/packages/fos_elastica.yaml):

    fos_elastica:
        clients:
            default:  # Client name
                host: '%env(ELASTICSEARCH_HOST)%'
                port: '%env(ELASTICSEARCH_PORT)%'
                user: '%env(ELASTICSEARCH_USER)%'
                password: '%env(ELASTICSEARCH_PASSWORD)%'
                client_config:
                    ssl: true
                client_options:
                    retries: 3
    
  3. Define an Index (config/packages/fos_elastica.yaml):

    fos_elastica:
        indexes:
            app_product:  # Index name
                types:  # Document types
                    Product:
                        properties:
                            name: ~
                            price: ~
                        persistence:
                            driver: orm
                            model: App\Entity\Product
                            provider: ~
                            listener: ~
    
  4. First Use Case: Populate the index via CLI:

    php bin/console fos:elastica:populate
    

    Or programmatically:

    $this->container->get('fos_elastica.finder.app_product')->findAll();
    

Where to Look First

  • Documentation: Start here for setup, configuration, and usage.
  • Configuration Reference: Focus on fos_elastica.yaml for clients, indexes, and mappings.
  • Console Commands: Use fos:elastica:* commands for index management (e.g., populate, reset, reindex).
  • Event Listeners: Leverage Doctrine events (postPersist, postUpdate, postRemove) for automatic indexing.

Implementation Patterns

Core Workflows

1. Indexing Data

  • Automatic Indexing (via Doctrine listeners):

    fos_elastica:
        indexes:
            app_product:
                types:
                    Product:
                        persistence:
                            driver: orm
                            listener: true  # Enable automatic indexing
    
    • Triggers on postPersist, postUpdate, and postRemove events.
  • Manual Indexing:

    $product = new Product();
    $this->get('fos_elastica.object_persister.app_product')->persist($product);
    

2. Searching Data

  • Basic Search:

    $finder = $this->get('fos_elastica.finder.app_product');
    $results = $finder->find(['name' => 'Laptop']);
    
  • Paginated Search (using Pagerfanta):

    $finder = $this->get('fos_elastica.finder.app_product');
    $paginator = $finder->findPaginated(['name' => 'Laptop'], 1, 10);
    
  • Aggregations:

    $results = $finder->find(['aggregations' => ['price_avg' => ['avg' => ['field' => 'price']]]]);
    

3. Custom Mappings

Define custom mappings in fos_elastica.yaml:

fos_elastica:
    indexes:
        app_product:
            types:
                Product:
                    properties:
                        name:
                            type: text
                            analyzer: custom_analyzer
                        price:
                            type: float
                            scale: 2

4. Asynchronous Indexing

Use Symfony Messenger for background indexing:

fos_elastica:
    indexes:
        app_product:
            types:
                Product:
                    persistence:
                        driver: orm
                        listener: true
                        async: true  # Enable async indexing

5. Index Aliases

Manage aliases for zero-downtime reindexing:

fos_elastica:
    indexes:
        app_product:
            alias: product_index
            settings:
                analysis:
                    analyzer:
                        custom_analyzer:
                            type: custom
                            tokenizer: standard
                            filter: [lowercase, asciifolding]

Integration Tips

  1. Doctrine ORM Integration:

    • Enable listener: true in persistence config for automatic sync.
    • Use fos_elastica.doctrine.orm_listener for event-driven indexing.
  2. Symfony Serializer:

    • Configure serializer groups for partial indexing:
      fos_elastica:
          serializer:
              groups: [default, elastica]
      
  3. Custom Transformers:

    • Extend FOS\ElasticaBundle\Transformer\TransformerInterface to customize object-to-array conversion:
      class CustomProductTransformer implements TransformerInterface
      {
          public function transform($object, array $context = [])
          {
              return [
                  'name' => $object->getName(),
                  'price' => $object->getPrice(),
                  'tags' => $object->getTags()->toArray(),
              ];
          }
      }
      
    • Register in services.yaml:
      services:
          App\Transformer\CustomProductTransformer:
              tags: [fos_elastica.transformer, { alias: 'app_product', type: 'Product' }]
      
  4. Event Subscribers:

    • Listen to PostElasticaRequestEvent or ElasticaRequestExceptionEvent for query logging/debugging:
      use FOS\ElasticaBundle\Event\PostElasticaRequestEvent;
      
      class ElasticaSubscriber implements EventSubscriberInterface
      {
          public static function getSubscribedEvents()
          {
              return [
                  PostElasticaRequestEvent::NAME => 'onPostRequest',
              ];
          }
      
          public function onPostRequest(PostElasticaRequestEvent $event)
          {
              $request = $event->getRequest();
              $this->logger->info('Elastica Query:', ['query' => $request->getBody()]);
          }
      }
      
  5. Testing:

    • Use fos_elastica.test.client for in-memory testing:
      $client = $this->get('fos_elastica.test.client');
      $index = $client->getIndex('test_index');
      $index->create();
      

Gotchas and Tips

Pitfalls

  1. Configuration Changes:

    • Breaking changes in v7.x (e.g., hosts array instead of host, port, url).
    • Always check the upgrade guide.
  2. Dynamic vs. Static Mappings:

    • Dynamic mappings can lead to unexpected schema changes. Prefer static mappings for production:
      fos_elastica:
          indexes:
              app_product:
                  settings:
                      mapping:
                          dynamic: strict
      
  3. Index Aliases:

    • Aliases require careful management during reindexing. Use fos:elastica:reindex with --alias flag:
      php bin/console fos:elastica:reindex --alias=product_index --from=app_product_old --to=app_product_new
      
  4. Performance:

    • Bulk indexing can overwhelm Elasticsearch. Use batch_size in fos:elastica:populate:
      php bin/console fos:elastica:populate --batch-size=100
      
    • Avoid indexing large binary fields (e.g., images). Use references or hashes instead.
  5. Serializer Groups:

    • Forgetting to include fields in serializer groups will result in empty or partial indexing:
      #[Groups(['elastica'])]
      private $name;
      
  6. Doctrine Events:

    • Disabling listener: true does not remove existing Doctrine listeners. Manually clear them if needed:
      $this->get('fos_elastica.doctrine.orm_listener')->disable();
      
  7. Elasticsearch Version Mismatch:

    • FOSElasticaBundle v7.x requires Elasticsearch 8.x. Downgrade if using older versions.

Debugging Tips

  1. Enable Query Logging:

    fos_elastica:
        client:
            debug: '%kernel.debug%'
    

    Logs queries to var/log/dev.log (or prod.log in production if debug: true).

  2. Check Index Status:

    php bin/console fos:elastica:status
    
  3. Reindex Safely:

    • Use --dry-run to preview changes:
      php bin/console fos:elastica:reindex --dry-run
      
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.
bugban/symfony
beyonder-capi/workflow-extensions-bundle
beyonder-capi/job-queue-bundle
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin