Elasticsearch مع Laravel Scout
ابنِ وظيفة بحث نصّي كامل قوية.
الإعداد
composer require laravel/scout
composer require babenkoivan/elastic-scout-driver
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
إعداد البيئة
# .env
SCOUT_DRIVER=elastic
ELASTIC_HOST=localhost:9200
جعل النموذج قابلاً للبحث
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';
}
}
إعداد الفهرس
// 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'],
],
],
],
],
];
البحث
// 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 نتائج بحث سريعة وذات صلة على نطاق واسع.
التعليقات (0)
اترك تعليقًا
لا توجد تعليقات بعد. كن أول من يشارك أفكاره!