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

Elasticsearch Bundle Laravel Package

daniel-iwaniec/elasticsearch-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ongr/elasticsearch-bundle
    

    Ensure ONGRELASTICSEARCH_BUNDLE is enabled in config/bundles.php.

  2. Configure Elasticsearch Connection Add to config/packages/ongr_elasticsearch.yaml:

    ongr_elasticsearch:
        clients:
            default:
                url: '%env(ES_URL)%'
                index_name: 'your_index'
    
  3. Define a Document Entity

    use ONGR\ElasticsearchBundle\Annotation as ES;
    
    #[ES\Document]
    class Product
    {
        #[ES\Property(type: 'text')]
        private $name;
    
        #[ES\Property(type: 'integer')]
        private $price;
    }
    
  4. First Query

    use ONGR\ElasticsearchBundle\Result\ResultInterface;
    use ONGR\ElasticsearchBundle\Finder\PaginatedFinderInterface;
    
    $finder = $this->get('ongr_elasticsearch.finder.paginated');
    /** @var ResultInterface $result */
    $result = $finder->find(Product::class, ['name' => 'test']);
    

Implementation Patterns

Query Building (DSL)

Use the Domain-Specific Language (DSL) for complex queries:

use ONGR\ElasticsearchBundle\Finder\PaginatedFinderInterface;
use ONGR\ElasticsearchBundle\Query\Builder;

$queryBuilder = new Builder();
$queryBuilder
    ->from(Product::class)
    ->addQuery(
        $queryBuilder->bool()
            ->should(
                $queryBuilder->match()->field('name')->value('test'),
                $queryBuilder->range()->field('price')->gt(100)
            )
    )
    ->setSize(10);

$finder->findBy($queryBuilder->getQuery());

Document Management

  • Indexing: Use IndexManager to create/update indices:
    $indexManager = $this->get('ongr_elasticsearch.index_manager');
    $indexManager->createIndex(Product::class);
    
  • Bulk Operations: Leverage BulkIndexer for batch inserts:
    $bulkIndexer = $this->get('ongr_elasticsearch.bulk_indexer');
    $bulkIndexer->index($products); // Array of Product entities
    

Pagination & Iterators

  • Paginated Results:
    $paginatedFinder = $this->get('ongr_elasticsearch.finder.paginated');
    $results = $paginatedFinder->find(Product::class, [], 1, 10); // Page 1, 10 items
    
  • Cursor-Based Iteration:
    $cursorFinder = $this->get('ongr_elasticsearch.finder.cursor');
    $cursor = $cursorFinder->find(Product::class, ['price' => ['gt' => 0]]);
    foreach ($cursor as $product) {
        // Process each product
    }
    

CLI Workflow

  • Generate Document Classes:
    php bin/console ongr:es:document:generate --index=products --class=Product
    
  • Reindex Data:
    php bin/console ongr:es:reindex --index=products --entity=App\Entity\Product
    

Gotchas and Tips

Common Pitfalls

  1. Index Name Conflicts

    • Ensure index_name in config matches your document’s @Document annotation.
    • Override via annotation: @Document(indexName="custom_index").
  2. Mapping Mismatches

    • Regenerate mappings after schema changes:
      php bin/console ongr:es:mapping:regenerate
      
    • Debug with:
      $client = $this->get('ongr_elasticsearch.client');
      $client->indices()->getMapping(['index' => 'your_index']);
      
  3. Connection Issues

    • Validate ES_URL in .env (e.g., http://localhost:9200).
    • Use ONGRELASTICSEARCH_BUNDLE__CLIENTS__DEFAULT__TIMEOUT to adjust timeouts.
  4. Annotation Caching

    • Clear cache after adding new @ES\Property fields:
      php bin/console cache:clear
      

Debugging Tips

  • Enable Query Logging:
    ongr_elasticsearch:
        clients:
            default:
                logger: true
    
  • Inspect Raw Queries:
    $query = $finder->getQueryBuilder()->getQuery();
    dump($query->toArray()); // Raw Elasticsearch query
    

Extension Points

  1. Custom Query Builders Extend ONGRELASTICSEARCH\ElasticsearchBundle\Query\Builder for domain-specific logic.

  2. Event Subscribers Listen to ONGRELASTICSEARCH\ElasticsearchBundle\Event\IndexEvent for pre/post-index hooks:

    use ONGR\ElasticsearchBundle\Event\IndexEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class MySubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                IndexEvent::PRE_INDEX => 'onPreIndex',
            ];
        }
    
        public function onPreIndex(IndexEvent $event)
        {
            // Modify document before indexing
        }
    }
    
  3. Custom Index Managers Implement ONGRELASTICSEARCH\ElasticsearchBundle\Index\IndexManagerInterface for advanced index control.

Performance Tips

  • Bulk Indexing: Batch operations reduce overhead (e.g., 1000+ documents).
  • Avoid Over-Fetching: Use select() in queries to limit returned fields:
    $queryBuilder->select(['name', 'price']);
    
  • Use search_after for Deep Pagination:
    $queryBuilder->setSearchAfter([$lastSortValue]);
    
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