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

bangpound/elasticsearch-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require caxy/elasticsearch-bundle
    

    Update AppKernel.php to register the bundle:

    new Caxy\Bundle\ElasticsearchBundle\CaxyElasticsearchBundle(),
    
  2. Configure Elasticsearch: Add to config.yml:

    caxy_elasticsearch:
        client:
            default:
                hosts: ["localhost:9200"]
    
  3. First Use Case: Inject the client in a controller/service:

    use Caxy\Bundle\ElasticsearchBundle\Client\ClientInterface;
    
    class SearchController
    {
        public function search(ClientInterface $esClient)
        {
            $results = $esClient->search([
                'index' => 'your_index',
                'body'  => ['query' => ['match_all' => new \stdClass()]]
            ]);
            return $results;
        }
    }
    

Implementation Patterns

Dependency Injection

  • Service Injection: Prefer constructor injection for testability:
    public function __construct(ClientInterface $esClient) { ... }
    
  • Named Clients: Use named clients for multi-cluster setups:
    caxy_elasticsearch:
        client:
            named:
                analytics:
                    hosts: ["analytics-es:9200"]
    
    Access via:
    $this->container->get('caxy_elasticsearch_client.analytics');
    

Common Workflows

  1. Indexing Data:

    $esClient->index([
        'index' => 'products',
        'id'    => $productId,
        'body'  => $productData
    ]);
    
  2. Searching:

    $params = [
        'index' => 'products',
        'body'  => [
            'query' => [
                'bool' => [
                    'must' => [
                        ['match' => ['name' => 'laptop']],
                        ['range' => ['price' => ['gte' => 500]]]
                    ]
                ]
            ]
        ]
    ];
    $results = $esClient->search($params);
    
  3. Bulk Operations:

    $bulkBody = [];
    foreach ($products as $product) {
        $bulkBody[] = ['index' => ['_index' => 'products', '_id' => $product['id']]];
        $bulkBody[] = $product;
    }
    $esClient->bulk(['body' => $bulkBody]);
    
  4. Mapping Management:

    $esClient->indices()->create([
        'index' => 'products',
        'body'  => [
            'mappings' => [
                'properties' => [
                    'name'  => ['type' => 'text'],
                    'price' => ['type' => 'float']
                ]
            ]
        ]
    ]);
    

Integration Tips

  • Symfony Events: Trigger indexing/search actions via events (e.g., kernel.request).
  • Doctrine ORM: Use listeners to sync database changes to Elasticsearch.
  • API Platform: Extend ApiPlatform\Metadata\Operation to add Elasticsearch queries.

Gotchas and Tips

Pitfalls

  1. Host Configuration:

    • Ensure hosts in config.yml includes both IP and port (e.g., ["localhost:9200"]).
    • Avoid trailing slashes (e.g., localhost/ will fail).
  2. Connection Timeouts:

    • Default timeouts may be too low for slow networks. Override in config:
      caxy_elasticsearch:
          client:
              default:
                  hosts: ["localhost:9200"]
                  timeout: 30s
      
  3. Named Clients Override:

    • Named clients do not inherit default settings. Explicitly define all required options.
  4. Deprecated Methods:

Debugging

  • Enable Logging:
    caxy_elasticsearch:
        client:
            default:
                hosts: ["localhost:9200"]
                log_path: "%kernel.logs_dir%/elasticsearch.log"
                log_level: Logger::DEBUG
    
  • Check Responses: Always inspect $results['hits'] and $results['_shards'] for errors:
    if (isset($results['error'])) {
        throw new \RuntimeException($results['error']['reason']);
    }
    

Extension Points

  1. Custom Client Classes: Extend Caxy\Bundle\ElasticsearchBundle\Client\Client to add domain-specific methods:

    class CustomClient extends Client
    {
        public function searchByName($index, $name)
        {
            return $this->search([
                'index' => $index,
                'body'  => ['query' => ['match' => ['name' => $name]]]
            ]);
        }
    }
    

    Register in config.yml:

    caxy_elasticsearch:
        client:
            named:
                custom:
                    class: App\Service\CustomClient
                    hosts: ["localhost:9200"]
    
  2. Event Subscribers: Listen to CaxyElasticsearchBundleEvents::CLIENT_INITIALIZED to modify the client instance:

    $subscriber = new class implements EventSubscriberInterface {
        public static function getSubscribedEvents()
        {
            return [
                'caxy_elasticsearch.client_initialized' => 'onClientInitialized'
            ];
        }
        public function onClientInitialized(ClientInitializedEvent $event)
        {
            $event->setClient($this->addCustomLogic($event->getClient()));
        }
    };
    
  3. Async Indexing: Use Symfony’s Messenger component to queue indexing tasks:

    $message = new IndexProductMessage($productId, $productData);
    $this->messageBus->dispatch($message);
    

    Process in a worker with the Elasticsearch client.

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