Elasticsearch with Laravel Scout
Build powerful full-text search functionality.
Setup
composer require laravel/scout
composer require babenkoivan/elastic-scout-driver
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
Configure Environment
# .env
SCOUT_DRIVER=elastic
ELASTIC_HOST=localhost:9200
Make Model Searchable
use Laravel\Scout\Searchable;
class Article extends Model
{
use Searchable;
public function toSearchableArray()
{
return [
'id' => $this->id,
'title' => $this->title,
'content' => $this->content,
'author' => $this->author->name,
'tags' => $this->tags->pluck('name'),
'published_at' => $this->published_at,
];
}
public function searchableAs()
{
return 'articles_index';
}
}
Index Configuration
// config/elastic.scout_driver.php
return [
'indexes' => [
'articles_index' => [
'settings' => [
'analysis' => [
'analyzer' => [
'custom_analyzer' => [
'type' => 'custom',
'tokenizer' => 'standard',
'filter' => ['lowercase', 'snowball'],
],
],
],
],
'mappings' => [
'properties' => [
'title' => ['type' => 'text', 'analyzer' => 'custom_analyzer'],
'content' => ['type' => 'text'],
'published_at' => ['type' => 'date'],
],
],
],
],
];
Searching
// Basic search
$articles = Article::search('laravel tutorial')->get();
// With filters
$articles = Article::search($query)
->where('author_id', $authorId)
->orderBy('published_at', 'desc')
->paginate(20);
// Advanced query
$articles = Article::search($query, function ($client, $body) {
$body['query']['bool']['must'][] = [
'range' => ['published_at' => ['gte' => 'now-30d']]
];
return $client->search(['index' => 'articles', 'body' => $body]);
})->get();
Elasticsearch provides fast, relevant search results at scale.
Comments (0)
Leave a Comment
No comments yet. Be the first to share your thoughts!