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.
Installation
composer require delormejonathan/elastica
composer.json for autoload.psr-4).Basic Configuration
localhost:9200).$client = new \Elastica\Client([
'host' => 'localhost',
'port' => 9200,
]);
First Use Case: Indexing a Model
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);
}
}
AppServiceProvider).Indexing Data
$repository->indexPost(1, [
'title' => 'Laravel Elasticsearch',
'body' => 'Full-text search with Elastica...',
'tags' => ['laravel', 'elasticsearch'],
]);
$bulk = $index->getBulk();
foreach ($posts as $post) {
$bulk->addDocument($post->toElasticArray());
}
$bulk->send();
Searching
$query = new \Elastica\Query\Match();
$query->setFieldQuery('title', 'Laravel');
$results = $index->search($query);
$results->setSize(10)->setFrom(0);
Syncing with Database
saved, deleted):
Post::saved(function ($post) {
app(PostElasticRepository::class)->indexPost($post->id, $post->toElasticArray());
});
Mapping Management
$index->getType('posts')->setProperty('title', \Elastica\Type::PROPERTY_TYPE_TEXT);
$index->getType('posts')->setProperty('tags', \Elastica\Type::PROPERTY_TYPE_KEYWORD);
$index->createType('posts');
try {
$index->addDocument($document);
} catch (\Elastica\Exception\ConnectionException $e) {
Log::error('Elasticsearch connection failed: ' . $e->getMessage());
}
Deprecated Methods
Elastica\Type is deprecated in favor of Elastica\Index\Type.No Laravel-Specific Features
Connection Issues
if (!$client->ping()) {
throw new \RuntimeException('Elasticsearch connection failed');
}
Mapping Conflicts
updateTypeMapping instead of createType:
$index->getType('posts')->updateTypeMapping();
$client = new \Elastica\Client([
'host' => 'localhost',
'logger' => new \Elastica\Logger\File('/path/to/elastica.log'),
]);
$data = array_filter($rawData, fn($value) => $value !== null);
Custom Analyzers
$type->setProperty('custom_field', \Elastica\Type::PROPERTY_TYPE_TEXT);
$type->setAnalyzer('custom_field', 'custom_analyzer');
$index->addAnalyzer('custom_analyzer', [
'tokenizer' => 'standard',
'filter' => ['lowercase', 'asciifolding'],
]);
Aggregations
$query = new \Elastica\Query\MatchAll();
$results = $index->search($query);
$results->addAggregation('tags', new \Elastica\Aggregation\Terms('tags'));
Bulk Operations
$bulk = $index->getBulk();
foreach ($items as $item) {
$bulk->addDocument($item->toElasticArray());
}
$bulk->send();
How can I help you explore Laravel packages today?