ElasticLens is a Laravel package that integrates Elasticsearch with Eloquent models. It provides advanced search capabilities while maintaining Laravel's familiar syntax. It works in tandem with the laravel-elasticsearch
package, allowing developers to perform full-text searches, manage index migrations, and customize field mappings easily.
User::search('loves espressos');
ElasticLens introduces an Index-Model
that mirrors your base Eloquent model. This model automatically synchronizes with your database, ensuring changes are reflected in your Elasticsearch index. For example, a User
model would have a corresponding IndexedUser
model, enabling efficient search operations:
User::viaIndex()->searchPhrase('loves dogs')->where('status', 'active')->get();
This approach allows for complex queries using Elasticsearch's powerful search features while maintaining the simplicity of Eloquent. Here are a few more advanced examples:
// Basic search term with limitsUser::viaIndex()->searchTerm('nara') ->where('state','active') ->limit(3)->get(); // Phrase searchUser::viaIndex()->searchPhrase('Ice bathing') ->orderByDesc('created_at') ->limit(5)->get(); // Boosting term fieldsUser::viaIndex()->searchTerm('David',['first_name^3', 'last_name^2', 'bio'])->get(); // Geolocation filteringUser::viaIndex()->where('status', 'active') ->filterGeoPoint('home.location', '5km', [0, 0]) ->orderByGeo('home.location',[0, 0]) ->get();
All of the above code snippets come from the project's readme examples.
Model Setup
Once you've installed this package, it works by adding the Indexable
trait to a model you want to index in Elasticsearch:
use PDPhilip\ElasticLens\Indexable; class User extends Eloquent implements Authenticatable, CanResetPassword{ use Indexable; // ...}
Next, you can create an index model using the php artisan lens:make User
command:
namespace App\Models\Indexes; use PDPhilip\ElasticLens\IndexModel; class IndexedUser extends IndexModel{}
This command generates an IndexedUser
model in the App\Models\Indexes
namespace, which handles the Elasticsearch indexing for the User
model.
Main Features
- Zero Configuration Setup: Quickly integrate Elasticsearch with minimal setup.
- Eloquent-Like Querying: Utilize familiar Eloquent syntax for complex search queries.
- Custom Field Mapping: Define how fields and relationships are indexed.
- Index Migrations: Manage Elasticsearch index versions and migrations.
- Model Observers: Automatically sync changes from your Eloquent models to Elasticsearch.
- Artisan CLI Tools: Commands for managing index health, migrations, and more.
Learn More
For detailed documentation and advanced usage, visit the ElasticLens GitHub repository. The official documentation has extensive examples and details of all available features.