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

Solr Bundle Laravel Package

daanbiesterbos/solr-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require daanbiesterbos/solr-bundle
    
  2. Enable the Bundle Add to config/bundles.php:

    return [
        // ...
        DaanBiesterbos\SolrBundle\SolrBundle::class => ['all' => true],
    ];
    
  3. Configure Solr Connection Define Solr host in config/packages/solr.yaml:

    solr:
        client:
            host: 'http://localhost:8983/solr'
            core: 'your_core_name'
    
  4. Annotate an Entity Use @Solr\Document and @Solr\Field annotations on a model (e.g., Product):

    use DaanBiesterbos\SolrBundle\Annotation as Solr;
    
    /**
     * @Solr\Document(index="products")
     */
    class Product
    {
        /**
         * @Solr\Field(type="text_general")
         */
        private $name;
    
        // ...
    }
    
  5. First Indexing Run a console command to index entities:

    php bin/console solr:index --entity=App\Entity\Product
    

First Use Case: Querying Solr

Inject the SolrClient and query:

use DaanBiesterbos\SolrBundle\Client\SolrClientInterface;

class ProductController
{
    public function __construct(private SolrClientInterface $solrClient) {}

    public function search(Request $request)
    {
        $query = $request->query->get('q');
        $results = $this->solrClient->search($query, 'products');

        return $this->render('product/search.html.twig', [
            'results' => $results->getResults(),
        ]);
    }
}

Implementation Patterns

Workflows

  1. Indexing Entities

    • Manual Indexing: Use solr:index command for one-time syncs.
    • Automatic Indexing: Implement Solr\IndexableInterface and trigger indexing in entity lifecycle events (e.g., postPersist):
      use DaanBiesterbos\SolrBundle\Annotation as Solr;
      
      /**
       * @Solr\Document(index="products")
       */
      class Product implements Solr\IndexableInterface
      {
          public function isIndexable(): bool
          {
              return true; // Always index this entity
          }
      }
      
    • Batch Indexing: Use SolrClient::indexEntities() for bulk operations:
      $this->solrClient->indexEntities(Product::class, ['id' => [1, 2, 3]]);
      
  2. Querying Data

    • Basic Search:
      $results = $this->solrClient->search('laptop', 'products');
      
    • Filtered Search:
      $results = $this->solrClient->search('laptop', 'products', [
          'fq' => ['price:[100 TO 1000]', 'category:electronics'],
      ]);
      
    • Pagination:
      $results = $this->solrClient->search('laptop', 'products', [
          'start' => 0,
          'rows' => 10,
      ]);
      
  3. Updating/Deleting

    • Soft Delete: Use a deleted_at field and filter queries:
      $results = $this->solrClient->search('laptop', 'products', [
          'fq' => ['deleted_at:[* TO *]'], // Exclude deleted
      ]);
      
    • Hard Delete: Reindex without the entity or use SolrClient::deleteById():
      $this->solrClient->deleteById('products', 123);
      

Integration Tips

  1. Symfony Forms Use Solr suggestions for autocomplete:

    $suggestions = $this->solrClient->suggest('lapt', 'products');
    
  2. Event Listeners Listen for Solr\Event\IndexEvent to customize indexing logic:

    use DaanBiesterbos\SolrBundle\Event\IndexEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class CustomIndexSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                'solr.index' => 'onIndex',
            ];
        }
    
        public function onIndex(IndexEvent $event)
        {
            $entity = $event->getEntity();
            // Modify $entity->getData() before indexing
        }
    }
    
  3. Doctrine Integration Use Solr\IndexableInterface with Doctrine lifecycle callbacks:

    // src/EventSubscriber/ProductSubscriber.php
    use Doctrine\Common\EventSubscriber;
    use Doctrine\ORM\Event\LifecycleEventArgs;
    
    class ProductSubscriber implements EventSubscriber
    {
        public function postPersist(Product $product, LifecycleEventArgs $args)
        {
            $this->solrClient->indexEntity($product);
        }
    }
    
  4. Custom Fields Define dynamic fields in Solr schema and map them in your entity:

    /**
     * @Solr\Field(type="text_general")
     */
    private $customField;
    

Gotchas and Tips

Pitfalls

  1. Performance Issues

    • Problem: Large datasets may cause timeouts or memory issues.
    • Fix: Use batch indexing (indexEntities) and optimize Solr config (e.g., maxBooleanClauses, autoCommit).
    • Tip: Monitor Solr logs (/solr/admin/cores?indexInfo=true) for slow queries.
  2. Schema Mismatches

    • Problem: Fields in your entity don’t match the Solr schema.
    • Fix: Ensure @Solr\Field(type="...") matches your Solr schema.xml types (e.g., text_general, int, date).
    • Debug: Use solr:schema:dump to inspect the schema:
      php bin/console solr:schema:dump
      
  3. Caching Queries

    • Problem: Repeated identical queries may hit Solr limits.
    • Fix: Cache results in Symfony cache (e.g., cache:app):
      $cacheKey = md5($query . serialize($filters));
      $results = $this->cache->get($cacheKey, function() use ($query, $filters) {
          return $this->solrClient->search($query, 'products', $filters);
      });
      
  4. Entity Changes Not Reflected

    • Problem: Updated entities aren’t reflected in Solr.
    • Fix: Reindex manually or implement postUpdate in Doctrine listeners:
      public function postUpdate(Product $product, LifecycleEventArgs $args)
      {
          $this->solrClient->indexEntity($product);
      }
      
  5. Deprecated Annotations

    • Problem: Original bundle annotations may still appear in docs.
    • Fix: Use DaanBiesterbos\SolrBundle\Annotation namespace explicitly.

Debugging

  1. Enable Solr Logging Add to config/packages/solr.yaml:

    solr:
        client:
            debug: true
    

    Logs will appear in var/log/dev.log.

  2. Raw Solr Queries Use SolrClient::createQuery() to inspect raw Solr requests:

    $query = $this->solrClient->createQuery('laptop', 'products');
    $rawQuery = $query->getQuery();
    
  3. Solr Admin UI Access http://localhost:8983/solr/#/~collections to:

    • Check core status.
    • Analyze query performance.
    • View indexed documents.

Extension Points

  1. Custom Query Builders Extend Solr\Query\QueryBuilder to add domain-specific methods:

    use DaanBiesterbos\SolrBundle\Query\QueryBuilder;
    
    class ProductQueryBuilder extends QueryBuilder
    {
        public function inStock()
        {
            $this->addFilterQuery('stock:[1 TO *]');
            return $this;
        }
    }
    

    Register as a service:

    services:
        App\Solr\Query\ProductQueryBuilder:
            tags: ['solr.query_builder']
    
  2. Dynamic Field Mapping Override Solr\Indexer\Indexer to handle dynamic fields:

    use DaanBiesterbos\SolrBundle\Indexer\IndexerInterface;
    
    class CustomIndexer implements IndexerInterface
    {
        public function indexEntity(object $entity, string $core)
        {
            $data = [];
            foreach ($entity as $property =>
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui