Installation
composer require awd-studio/es-lib
Publish the config (if available) with:
php artisan vendor:publish --provider="AwdStudio\EsLib\EsLibServiceProvider"
Basic Usage
The package provides Elasticsearch utilities. Start by configuring it in config/es-lib.php:
'connections' => [
'default' => [
'hosts' => ['http://localhost:9200'],
'index' => 'your_app_index',
],
],
First Query
Use the Elasticsearch facade to run a simple search:
use AwdStudio\EsLib\Facades\Elasticsearch;
$results = Elasticsearch::search('your_query', ['index' => 'your_app_index']);
Indexing Models
Use the ElasticsearchModel trait to sync Laravel models with Elasticsearch:
use AwdStudio\EsLib\Traits\ElasticsearchModel;
class Product extends Model
{
use ElasticsearchModel;
protected $esIndex = 'products';
}
Sync data on model events:
Product::created(fn ($product) => $product->syncToEs());
Query Builder Chain methods for complex queries:
$results = Elasticsearch::search('laptop')
->filter('price', '>=', 500)
->sortBy('created_at', 'desc')
->paginate(10);
Bulk Operations
Use Elasticsearch::bulk() for batch indexing:
$data = Product::all()->map(fn ($p) => $p->toEsArray());
Elasticsearch::bulk($data, 'products');
es-synced or es-failed events for post-sync actions.EsLibMiddleware to inject Elasticsearch data into requests.Index Mapping Conflicts
toEsArray() returns fields matching the Elasticsearch mapping. Use Elasticsearch::index()->putMapping() to verify/update mappings.Rate Limiting
Elasticsearch::bulk()->chunk(500) to batch requests.Connection Timeouts
config/es-lib.php:
'retry' => [
'max_attempts' => 3,
'delay' => 100, // ms
],
Elasticsearch::debug(true); // Logs raw queries to storage/logs/es.log
docker run -p 9200:9200 elasticsearch:8).Custom Analyzers
Extend the Analyzer class to add domain-specific tokenizers:
Elasticsearch::analyzer()->custom('custom_analyzer', [
'type' => 'custom',
'tokenizer' => 'standard',
'filter' => ['lowercase', 'asciifolding'],
]);
Hooks
Override syncToEs() in your model to add pre/post-processing:
protected function prepareForEs()
{
$this->esData['slug'] = Str::slug($this->name);
}
Async Processing Use Laravel Queues to offload syncs:
Product::created(fn ($p) => SyncToEsJob::dispatch($p));
How can I help you explore Laravel packages today?