Backend Development 1 min read 834 views

Implementing Search with Elasticsearch and Laravel Scout

Build powerful full-text search with Elasticsearch and Laravel Scout. Learn about indexing, queries, and relevance tuning.

E
Search functionality

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.

Share this article:
ES

Written by Edrees Salih

Full-stack software engineer with 9 years of experience. Passionate about building scalable solutions and sharing knowledge with the developer community.

View Profile

Comments (0)

Leave a Comment

Your email will not be published.

No comments yet. Be the first to share your thoughts!