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

Search Bundle Laravel Package

blast-project/search-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle Add to composer.json:

    "require": {
        "blast-project/search-bundle": "^1.0"
    }
    

    Run composer require blast-project/search-bundle.

  2. Configure ElasticSearch Ensure ElasticSearch is running (locally via Docker or a remote instance). Update config/packages/blast_search.yaml with your ElasticSearch host:

    blast_search:
        client:
            host: 'http://localhost:9200'  # or your ElasticSearch endpoint
    
  3. First Use Case: Indexing a Model Define a searchable entity (e.g., Product) and annotate it with #[Searchable]:

    use Blast\SearchBundle\Annotation\Searchable;
    
    #[Searchable]
    class Product {}
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Blast\SearchBundle\BlastSearchBundle::class => ['all' => true],
    ];
    

    Run the indexer command to populate ElasticSearch:

    php bin/console blast:search:index
    

Implementation Patterns

Workflows

  1. Indexing Data

    • Manual Trigger: Use the CLI command for one-time indexing:
      php bin/console blast:search:index Product
      
    • Automatic Sync: Subscribe to entity events (e.g., postPersist, postUpdate) via Doctrine listeners to keep ElasticSearch in sync:
      use Blast\SearchBundle\Event\IndexerEvent;
      use Symfony\Component\EventDispatcher\EventSubscriberInterface;
      
      class ProductIndexSubscriber implements EventSubscriberInterface
      {
          public static function getSubscribedEvents(): array
          {
              return [
                  IndexerEvent::POST_PERSIST => 'indexProduct',
                  IndexerEvent::POST_UPDATE => 'indexProduct',
              ];
          }
      
          public function indexProduct(IndexerEvent $event): void
          {
              $event->getIndexer()->index($event->getEntity());
          }
      }
      
  2. Searching Data

    • Use the SearchQueryBuilder to construct queries:
      use Blast\SearchBundle\Query\SearchQueryBuilder;
      
      $query = (new SearchQueryBuilder())
          ->select('id', 'name')
          ->from(Product::class)
          ->where('name', 'LIKE', '%phone%')
          ->limit(10);
      
      $results = $query->getResults();
      
  3. Custom Mappings Override default mappings in config/packages/blast_search.yaml:

    blast_search:
        mappings:
            Product:
                properties:
                    name:
                        type: text
                        analyzer: custom_analyzer
                    price:
                        type: float
    

Integration Tips

  • Leverage FOSElasticaBundle: If using FOSElasticaBundle, alias the blast_search.client service to fos_elastica.client for compatibility.
  • Pagination: Use SearchQueryBuilder::setPage() and setLimit() for paginated results.
  • Aggregations: Extend SearchQueryBuilder to support aggregations:
    $query->addAggregation('avg_price', 'avg', 'price');
    

Gotchas and Tips

Pitfalls

  1. ElasticSearch Version Mismatch

    • Avoid ElasticSearch 6.x due to incompatibility with FOSElasticaBundle (as noted in the README). Use 7.x or 8.x.
    • Debug connection issues with:
      curl -X GET "http://localhost:9200/"
      
      Ensure the response includes "version" and "tagline".
  2. Indexing Delays

    • If using automatic sync, ensure Doctrine events are dispatched. Verify with:
      $eventDispatcher->dispatch(new IndexerEvent($entity, IndexerEvent::POST_PERSIST));
      
    • For large datasets, batch indexing with Indexer::indexMany().
  3. Mapping Conflicts

    • If mappings fail, drop and recreate the index:
      php bin/console blast:search:drop-index Product
      php bin/console blast:search:create-index Product
      php bin/console blast:search:index Product
      

Debugging

  • Enable Debug Logging Add to config/packages/dev/blast_search.yaml:

    blast_search:
        client:
            logging: true
    

    Check logs in var/log/dev.log for ElasticSearch queries.

  • Test Queries Use Kibana (port 5601 in the Docker setup) to manually test queries against your index.

Extension Points

  1. Custom Indexers Implement Blast\SearchBundle\Indexer\IndexerInterface for custom logic:

    class CustomIndexer implements IndexerInterface
    {
        public function index($entity): void
        {
            // Custom indexing logic
        }
    }
    

    Register it in services.yaml:

    services:
        Blast\SearchBundle\Indexer\CustomIndexer:
            tags: ['blast_search.indexer']
    
  2. Pre/Post Indexing Hooks Use Symfony events to modify entities before indexing:

    # config/services.yaml
    services:
        App\EventListener\PreIndexListener:
            tags:
                - { name: kernel.event_listener, event: blast.search.pre_index, method: onPreIndex }
    
  3. Async Indexing For performance, offload indexing to a queue (e.g., Symfony Messenger):

    use Symfony\Component\Messenger\MessageBusInterface;
    
    $bus->dispatch(new IndexMessage($entity));
    

    Create a handler:

    class IndexHandler
    {
        public function __invoke(IndexMessage $message)
        {
            $indexer->index($message->getEntity());
        }
    }
    
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