Weave 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

Elastica Laravel Package

delormejonathan/elastica

Laravel-friendly PHP integration for the Elastica Elasticsearch client. Provides simple configuration, service container bindings, and convenient access to an Elastica client within your app for running searches and managing indexes.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require delormejonathan/elastica
    
    • Verify the package is autoloaded (check composer.json for autoload.psr-4).
  2. Basic Configuration

    • No config file is required, but ensure Elasticsearch is running locally or via a cloud provider (e.g., localhost:9200).
    • Initialize the client in a service provider or bootstrap file:
      $client = new \Elastica\Client([
          'host' => 'localhost',
          'port' => 9200,
      ]);
      
  3. First Use Case: Indexing a Model

    • Create a repository class to handle Elasticsearch operations:
      use Elastica\Client;
      use Elastica\Document;
      
      class PostElasticRepository {
          protected $client;
      
          public function __construct(Client $client) {
              $this->client = $client;
          }
      
          public function indexPost($postId, array $data) {
              $index = $this->client->getIndex('posts');
              $document = $index->getDocument($postId);
              $document->setData($data);
              $index->addDocument($document);
          }
      }
      
    • Register the repository in Laravel’s IoC container (e.g., AppServiceProvider).

Implementation Patterns

Common Workflows

  1. Indexing Data

    • Use repositories to abstract Elasticsearch logic. Example:
      $repository->indexPost(1, [
          'title' => 'Laravel Elasticsearch',
          'body'  => 'Full-text search with Elastica...',
          'tags'  => ['laravel', 'elasticsearch'],
      ]);
      
    • Batch indexing for performance:
      $bulk = $index->getBulk();
      foreach ($posts as $post) {
          $bulk->addDocument($post->toElasticArray());
      }
      $bulk->send();
      
  2. Searching

    • Build queries dynamically:
      $query = new \Elastica\Query\Match();
      $query->setFieldQuery('title', 'Laravel');
      $results = $index->search($query);
      
    • Paginate results:
      $results->setSize(10)->setFrom(0);
      
  3. Syncing with Database

    • Trigger Elasticsearch updates on model events (saved, deleted):
      Post::saved(function ($post) {
          app(PostElasticRepository::class)->indexPost($post->id, $post->toElasticArray());
      });
      
  4. Mapping Management

    • Define mappings once (e.g., in a migration or service provider):
      $index->getType('posts')->setProperty('title', \Elastica\Type::PROPERTY_TYPE_TEXT);
      $index->getType('posts')->setProperty('tags', \Elastica\Type::PROPERTY_TYPE_KEYWORD);
      $index->createType('posts');
      

Integration Tips

  • Laravel Scout Alternative: Use Elastica for custom search logic where Scout’s limitations apply (e.g., complex aggregations).
  • Caching: Cache frequent queries or results to reduce Elasticsearch load.
  • Error Handling: Wrap operations in try-catch blocks to handle connection issues gracefully:
    try {
        $index->addDocument($document);
    } catch (\Elastica\Exception\ConnectionException $e) {
        Log::error('Elasticsearch connection failed: ' . $e->getMessage());
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Methods

    • The package is outdated (last release: 2016). Some Elastica methods may be deprecated or renamed. Check the Elastica docs for updates.
    • Example: Elastica\Type is deprecated in favor of Elastica\Index\Type.
  2. No Laravel-Specific Features

    • Unlike Scout, this package lacks built-in Laravel integrations (e.g., model observers, queue jobs). You’ll need to implement these manually.
  3. Connection Issues

    • Elasticsearch timeouts or misconfigurations (e.g., wrong host/port) will silently fail. Always validate connections:
      if (!$client->ping()) {
          throw new \RuntimeException('Elasticsearch connection failed');
      }
      
  4. Mapping Conflicts

    • If mappings exist, avoid recreating them. Use updateTypeMapping instead of createType:
      $index->getType('posts')->updateTypeMapping();
      

Debugging Tips

  • Enable Logging: Configure Elastica’s logger to debug queries:
    $client = new \Elastica\Client([
        'host' => 'localhost',
        'logger' => new \Elastica\Logger\File('/path/to/elastica.log'),
    ]);
    
  • Test Locally: Use Docker or a local Elasticsearch instance to avoid cloud provider quirks.
  • Validate Data: Sanitize input before indexing to avoid malformed documents:
    $data = array_filter($rawData, fn($value) => $value !== null);
    

Extension Points

  1. Custom Analyzers

    • Extend search capabilities by defining custom analyzers in mappings:
      $type->setProperty('custom_field', \Elastica\Type::PROPERTY_TYPE_TEXT);
      $type->setAnalyzer('custom_field', 'custom_analyzer');
      $index->addAnalyzer('custom_analyzer', [
          'tokenizer' => 'standard',
          'filter'    => ['lowercase', 'asciifolding'],
      ]);
      
  2. Aggregations

    • Use Elastica’s aggregation features for analytics:
      $query = new \Elastica\Query\MatchAll();
      $results = $index->search($query);
      $results->addAggregation('tags', new \Elastica\Aggregation\Terms('tags'));
      
  3. Bulk Operations

    • Optimize performance with bulk APIs for large datasets:
      $bulk = $index->getBulk();
      foreach ($items as $item) {
          $bulk->addDocument($item->toElasticArray());
      }
      $bulk->send();
      
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.
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode
jjsquady/round-robin