تطوير الواجهة الخلفية 1 دقيقة للقراءة 881 مشاهدات

تطبيق البحث مع Elasticsearch وLaravel Scout

ابنِ بحثاً نصياً كاملاً قوياً مع Elasticsearch وLaravel Scout. تعلّم عن الفهرسة والاستعلامات وضبط الصلة.

Search functionality

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 نتائج بحث سريعة وذات صلة على نطاق واسع.

مشاركة هذه المقالة:
ES
كتبه

Edrees Salih

مهندس برمجيات متكامل يتمتع بخبرة 9 سنوات. شغوف ببناء حلول قابلة للتطوير ومشاركة المعرفة مع مجتمع المطورين.

عرض الملف الشخصي

التعليقات (0)

اترك تعليقًا

لن يتم نشر بريدك الإلكتروني.

لا توجد تعليقات بعد. كن أول من يشارك أفكاره!

مقالات ذات صلة

مقالات ذات صلة

هل تحتاج مساعدة في مشروعك؟

احجز استشارة مجانية لمدة 30 دقيقة لمناقشة تحدياتك التقنية واستكشاف الحلول معًا.