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

delormejonathan/elastica-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require friendsofsymfony/elastica-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        FriendsOfSymfony\ElasticaBundle\FOSElasticaBundle::class => ['all' => true],
    ];
    
  2. Configure Elasticsearch Client (config/packages/fos_elastica.yaml):

    fos_elastica:
        clients:
            default: { host: localhost, port: 9200 }
        indexes:
            app:
                types:
                    product:
                        properties:
                            name: ~
                            price: ~
                        persistence:
                            driver: orm
                            model: App\Entity\Product
                            provider: ~
                            listener: ~
                            repository: ~
    
  3. First Use Case:

    • Index a Model:
      php bin/console fos:elastica:populate
      
    • Search via Repository:
      $repository = $this->getDoctrine()
          ->getRepository(Product::class)
          ->getElasticaRepository();
      $results = $repository->find('search_term');
      

Implementation Patterns

Core Workflows

  1. Automatic Indexing:

    • Use Doctrine event listeners (e.g., prePersist, preUpdate, preRemove) to sync Elasticsearch with your database.
    • Configure in YAML:
      fos_elastica:
          indexes:
              app:
                  types:
                      product:
                          persistence:
                              listener: true  # Auto-index on Doctrine events
      
  2. Custom Mappings:

    • Override default mappings via annotations or YAML:
      properties:
          name:
              type: text
              analyzer: custom_analyzer
      
    • Use @Elastica\Property in entities:
      use FOSElasticaBundle\Elastica\Annotation as Elastica;
      
      /**
       * @Elastica\Property(type="integer")
       */
      private $stock;
      
  3. Search Integration:

    • Basic Query:
      $query = new \Elastica\Query\Match();
      $query->setFieldQuery('name', 'search_term');
      $results = $repository->search($query);
      
    • Aggregations:
      $aggregation = new \Elastica\Aggregation\Terms('categories');
      $aggregation->setField('category');
      $results = $repository->search(new \Elastica\Query(), $aggregation);
      
  4. Bulk Operations:

    • Use fos:elastica:populate for initial indexing.
    • For updates, leverage Doctrine listeners or manual reindexing:
      php bin/console fos:elastica:reindex
      
  5. Pagination:

    • Use setFrom() and setSize() in queries:
      $query->setFrom(0)->setSize(10);
      

Integration Tips

  1. Symfony Forms:

    • Bind Elasticsearch results to forms for autocomplete:
      $builder->add('name', EntityType::class, [
          'class' => Product::class,
          'query_builder' => function (ProductRepository $repo) {
              return $repo->createElasticaQueryBuilder('search_term')->select('p');
          },
      ]);
      
  2. APIs:

    • Expose search endpoints via API Platform or custom controllers:
      #[Route('/search', name: 'app_search', methods: ['GET'])]
      public function search(Request $request, ProductElasticaRepository $repo): JsonResponse
      {
          $query = new \Elastica\Query\Match();
          $query->setFieldQuery('name', $request->query->get('q'));
          $results = $repo->search($query);
          return new JsonResponse($results);
      }
      
  3. Cron Jobs:

    • Schedule periodic reindexing for large datasets:
      php bin/console fos:elastica:reindex --env=prod
      

Gotchas and Tips

Pitfalls

  1. Mapping Conflicts:

    • Elasticsearch mappings are immutable. Avoid changing field types after indexing.
    • Fix: Reindex data if mappings must change:
      php bin/console fos:elastica:reindex
      
  2. Listener Overhead:

    • Doctrine listeners trigger on every save(), which can slow down bulk operations.
    • Fix: Disable listeners during bulk inserts:
      $em->getEventManager()->removeEventListeners('prePersist');
      // Bulk operations...
      $em->getEventManager()->addEventListeners('prePersist');
      
  3. Pagination Limits:

    • Elasticsearch defaults to from=0 and size=10 for pagination. Large offsets (from) are inefficient.
    • Fix: Use search_after for deep pagination or implement keyset pagination.
  4. Case Sensitivity:

    • Default analyzers may not handle case sensitivity as expected.
    • Fix: Configure custom analyzers in Elasticsearch or use keyword fields:
      properties:
          sku:
              type: keyword  # Exact matches
      
  5. Propel Support:

    • Limited functionality; manual indexing may be required for Propel entities.

Debugging

  1. Check Index Status:

    curl -XGET 'http://localhost:9200/_cat/indices?v'
    
  2. Inspect Mappings:

    curl -XGET 'http://localhost:9200/app/_mapping?pretty'
    
  3. Enable Debugging:

    • Add to config/packages/dev/fos_elastica.yaml:
      fos_elastica:
          clients:
              default:
                  debug: true
      
  4. Log Queries:

    • Use Elastica’s Logger:
      $client->getLogger()->setLevel(\Psr\Log\LogLevel::DEBUG);
      

Extension Points

  1. Custom Providers:

    • Override Persistence\Provider\AbstractProvider to fetch data from non-Doctrine sources (e.g., APIs).
  2. Event Subscribers:

    • Extend indexing logic via fos_elastica.index events:
      $eventDispatcher->addListener(
          'fos_elastica.index',
          function (IndexEvent $event) {
              $event->getDocument()->setData('custom_field', 'value');
          }
      );
      
  3. Query Builders:

    • Create custom query builders for complex searches:
      class CustomQueryBuilder extends \FOSElasticaBundle\Elastica\QueryBuilder
      {
          public function withCustomFilter()
          {
              $this->addFilter(new \Elastica\Filter\Term('status', 'active'));
              return $this;
          }
      }
      
  4. Serializer Groups:

    • Control which fields are indexed via Symfony Serializer groups:
      fos_elastica:
          indexes:
              app:
                  types:
                      product:
                          persistence:
                              serializer:
                                  groups: ['elastica']
      
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