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

caxy/elasticsearch-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require caxy/elasticsearch-bundle:0.0.*
    

    Add the bundle to AppKernel.php:

    new Caxy\Bundle\ElasticsearchBundle\CaxyElasticsearchBundle(),
    
  2. Basic Configuration (config.yml):

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

    use Caxy\Bundle\ElasticsearchBundle\Client\ClientInterface;
    
    class SearchController extends Controller
    {
        public function searchAction(ClientInterface $client)
        {
            $params = [
                'index' => 'your_index',
                'body'  => ['query' => ['match_all' => new \stdClass()]]
            ];
            $response = $client->search($params);
            return $this->json($response);
        }
    }
    

Implementation Patterns

Dependency Injection

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

Common Workflows

  1. Indexing Documents:

    $params = [
        'index' => 'products',
        'type'  => 'product',
        'id'    => 123,
        'body'  => ['name' => 'Laptop', 'price' => 999.99]
    ];
    $this->client->index($params);
    
  2. Searching with Aggregations:

    $params = [
        'index' => 'products',
        'body'  => [
            'aggs' => [
                'avg_price' => ['avg' => ['field' => 'price']]
            ]
        ]
    ];
    $response = $this->client->search($params);
    
  3. Bulk Operations:

    $body = [
        ['index' => ['_index' => 'products', '_type' => 'product', '_id' => 1]],
        ['name' => 'Mouse', 'price' => 19.99],
        ['index' => ['_index' => 'products', '_type' => 'product', '_id' => 2]],
        ['name' => 'Keyboard', 'price' => 49.99]
    ];
    $this->client->bulk(['body' => $body]);
    

Integration Tips

  • Symfony Events: Trigger events on Elasticsearch operations (e.g., post-indexing):
    $dispatcher->dispatch('elasticsearch.index', new ElasticsearchEvent($params, $response));
    
  • Doctrine ORM: Sync Doctrine entities to Elasticsearch using lifecycle callbacks:
    // In your entity
    public function prePersist()
    {
        $this->syncToElasticsearch();
    }
    

Gotchas and Tips

Pitfalls

  1. Host Configuration:

    • Ensure hosts in config.yml includes both IP and port (e.g., localhost:9200), not just localhost.
    • Test connectivity manually:
      curl -X GET "localhost:9200/"
      
  2. Client Initialization:

    • The bundle does not auto-initialize the client on demand. Ensure the ClientInterface is injected where needed.
    • Avoid global static calls; prefer dependency injection.
  3. Logging:

    • Log paths (e.g., log_path) must be writeable by the PHP process. Use absolute paths:
      log_path: "%kernel.logs_dir%/elasticsearch.log"
      
  4. Deprecated Methods:

    • The package uses the Elasticsearch PHP client v1.x. If upgrading to v7/8, expect breaking changes (e.g., Client::search()Client::search() remains, but parameters may shift).

Debugging

  • Enable Debug Mode:
    caxy_elasticsearch:
        client:
            default:
                hosts: ["localhost:9200"]
                log_level: Logger::DEBUG
    
  • Check Raw Responses:
    $response = $this->client->search($params);
    error_log(print_r($response, true)); // Inspect full response
    

Extension Points

  1. Custom Client Classes: Override the default client class for extended functionality:

    caxy_elasticsearch:
        client:
            named:
                custom:
                    class: App\Service\CustomElasticsearchClient
                    hosts: ["localhost:9200"]
    
  2. Event Listeners: Subscribe to bundle events (e.g., elasticsearch.client.initialize):

    // services.yml
    services:
        app.elasticsearch.listener:
            class: App\EventListener\ElasticsearchListener
            tags:
                - { name: kernel.event_listener, event: elasticsearch.client.initialize, method: onClientInit }
    
  3. Configuration Overrides: Use environment variables for dynamic configs:

    hosts: ["%env(ES_HOST)%"]
    

    Set via .env:

    ES_HOST=elasticsearch:9200
    

Performance Tips

  • Bulk Indexing: Batch operations to reduce overhead:
    $bulkParams = ['body' => []];
    foreach ($entities as $entity) {
        $bulkParams['body'][] = ['index' => ['_index' => 'products', '_type' => 'product']];
        $bulkParams['body'][] = $entity->toArray();
    }
    $this->client->bulk($bulkParams);
    
  • Connection Pooling: Reuse the same client instance across requests (handled automatically via DI).
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