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

atoolo/search-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   Add the bundle via Composer:
   ```bash
   composer require sitepark/atoolo-search-bundle

Enable it in config/bundles.php:

return [
    // ...
    Sitepark\AtooloSearchBundle\AtooloSearchBundle::class => ['all' => true],
];
  1. Configuration Publish the default config:

    php artisan vendor:publish --tag=atoolo-search-config
    

    Update config/atoolo_search.yaml with your Solr connection details:

    solr:
        host: 'http://solr:8983/solr'
        core: 'atoolo'
    
  2. First Indexing Index a resource type (e.g., Article) via CLI:

    php artisan atoolo:search:index Article
    

    Or programmatically:

    use Sitepark\AtooloSearchBundle\Command\IndexCommand;
    $indexer = $this->get(IndexCommand::class);
    $indexer->handle(new ArrayObject(['Article']));
    
  3. Basic Search Use the SearchQueryBuilder to construct queries:

    use Sitepark\AtooloSearchBundle\Query\SearchQueryBuilder;
    
    $query = (new SearchQueryBuilder())
        ->addTerm('keyword')
        ->setPage(1)
        ->setLimit(10)
        ->build();
    
    $results = $this->get('atoolo_search.search_service')->search($query);
    

Implementation Patterns

Core Workflows

1. Indexing Resources

  • Batch Indexing: Use the IndexCommand for bulk operations (e.g., cron jobs):
    php artisan atoolo:search:index Article --batch-size=50
    
  • Single Resource Indexing: Trigger via event listeners or manually:
    $resource = $this->get('atoolo_resource.manager')->get('Article', 1);
    $this->get('atoolo_search.indexer')->index($resource);
    
  • Dynamic Field Mapping: Extend IndexSchema2xDocument to add custom fields:
    class CustomDocument extends IndexSchema2xDocument
    {
        public function getCustomField()
        {
            return $this->getResource()->getCustomAttribute();
        }
    }
    

2. Searching

  • Query Construction: Chain builders for complex queries:
    $query = (new SearchQueryBuilder())
        ->addTerm('laravel')
        ->addFilter('category', 'technology')
        ->addFacet('category')
        ->setSort('relevance')
        ->build();
    
  • Pagination & Facets: Handle results with:
    $results = $this->get('atoolo_search.search_service')->search($query);
    $facets = $results->getFacets();
    $total = $results->getTotal();
    
  • Spellcheck & Suggestions: Use SolrSuggest for autocomplete:
    $suggestions = $this->get('atoolo_search.solr_suggest')->suggest('laravle');
    

3. Advanced Features

  • Geospatial Search: Use GeoLocatedFilter for location-based queries:
    $query->addFilter(new GeoLocatedFilter(52.5200, 13.4050, 10)); // lat, lng, radius (km)
    
  • More Like This: Fetch similar resources:
    $similar = $this->get('atoolo_search.more_like_this')->find(123);
    
  • Query Templates: Reuse query logic via templates:
    # config/atoolo_search.yaml
    query_templates:
        featured_articles:
            filters:
                - { field: 'featured', value: 'true' }
            sort: 'sp_sortvalue desc'
    
    Then apply:
    $query->applyTemplate('featured_articles');
    

4. Event-Driven Indexing

  • Listen to resource events (e.g., ResourceUpdatedEvent) and trigger indexing:
    public function onResourceUpdated(ResourceUpdatedEvent $event)
    {
        $this->get('atoolo_search.indexer')->index($event->getResource());
    }
    

Integration Tips

Laravel Ecosystem

  • Service Container: Bind custom indexers or search services:
    $this->app->bind('custom.indexer', function () {
        return new CustomIndexer();
    });
    
  • API Resources: Transform search results with JsonResource:
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'teaser' => $this->teaser,
            'url' => route('articles.show', $this->id),
        ];
    }
    
  • Caching: Cache frequent queries or index snapshots:
    $cacheKey = 'search_results_' . md5($query->getQuery());
    return Cache::remember($cacheKey, 3600, function () use ($query) {
        return $this->get('atoolo_search.search_service')->search($query);
    });
    

Solr-Specific

  • Schema Customization: Extend IndexSchema2xDocument to map custom fields:
    class CustomDocument extends IndexSchema2xDocument
    {
        public function getCustomField()
        {
            return $this->getResource()->getCustomField();
        }
    }
    
    Register the mapper in services.yaml:
    services:
        Sitepark\AtooloSearchBundle\Document\IndexSchema2xDocument:
            arguments:
                $fieldMappers:
                    - '@custom.document_mapper'
    
  • Query Modifiers: Apply post-processing to queries:
    $query->addModifier(new BoostModifier('featured', 2.0));
    

Gotchas and Tips

Pitfalls

  1. Indexing Delays:

    • Issue: Background indexing may not reflect real-time changes.
    • Fix: Use sync mode for critical updates:
      php artisan atoolo:search:index Article --sync
      
    • Tip: Monitor queue workers (atoolo:search:worker) for async tasks.
  2. Field Mapping Errors:

    • Issue: Custom fields may not appear in Solr if not mapped.
    • Fix: Ensure IndexSchema2xDocument methods return the correct type (e.g., string, int).
    • Debug: Check Solr admin UI (/solr/#/atoolo/schema) for missing fields.
  3. Locale Handling:

    • Issue: Multi-language content may not index correctly.
    • Fix: Explicitly set the locale in queries:
      $query->setLocale('de');
      
    • Tip: Use atoolo_resource.locale_resolver to detect user locale.
  4. Permission Groups:

    • Issue: Protected resources may not index with correct groups.
    • Fix: Ensure include_groups is set in config/atoolo_search.yaml:
      indexer:
          include_groups: ['admin', 'editor']
      
  5. Solr Core Mismatch:

    • Issue: Queries fail if the Solr core doesn’t match the config.
    • Fix: Verify atoolo_search.solr.core in config/atoolo_search.yaml matches your Solr setup.

Debugging

  • Solr Logs: Enable debug mode in config/atoolo_search.yaml:

    debug: true
    

    Check Solr logs (/var/log/solr.log) for query errors.

  • Query Inspection: Dump the raw Solr query:

    $query = $searchService->buildQuery($searchQuery);
    dd($query->getSolrQuery());
    
  • Index Validation: Validate indexed documents:

    php artisan atoolo:search:validate Article
    

Extension Points

  1. Custom Indexers: Extend AbstractIndexer for specialized logic:

    class CustomIndexer extends AbstractIndexer
    {
        protected function getDocumentClass(): string
        {
            return CustomDocument::class;
        }
    }
    

    Register in services.yaml:

    services:
        custom.indexer:
            class: App\CustomIndexer
            tags: ['atoolo_search.indexer']
    
  2. Query Filters: Create custom filters (e.g., for tags):

    class TagFilter implements FilterInterface
    {
        public function apply(QueryBuilder $query, $value)
        {
            $query->addFilter('tags', $value);
        }
    }
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky