Laravel 全文搜索实战:用 Scout 与 Meilisearch 给模型加毫秒级检索

test12026-10-083 次阅读

为什么选 Meilisearch

Laravel Scout 把“搜索”抽象成模型上的一个可搜索接口,底层可接数据库 like、Algolia 或 Meilisearch。Meilisearch 是开源、开箱即用的本地搜索引擎,毫秒级返回,还自带分词、排序与高亮,适合自托管场景。

1 安装与配置

引入 scout 与 meilisearch 驱动,把默认驱动切到 meilisearch,并填好主机与密钥。

composer require laravel/scout:^10
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
composer require meilisearch/meilisearch-php
// config/scout.php
"driver" => "meilisearch",
"meilisearch" => [
    "host" => env("MEILISEARCH_HOST", "http://127.0.0.1:7700"),
    "key"  => env("MEILISEARCH_KEY"),
],

2 让模型可搜索

实现 Searchable 接口,用 toSearchableArray 决定哪些字段进索引,shouldBeSearchable 控制是否入索引。

use Laravel\Scout\Searchable;

class Post extends Model
{
    use Searchable;

    public function toSearchableArray(): array
    {
        return [
            "id"      => $this->id,
            "title"   => $this->title,
            "body"    => $this->body,
            "created" => $this->created_at->timestamp,
        ];
    }
}

3 导入索引与查询

先把存量数据推到 Meilisearch,再用 search 方法发起检索,链式调用支持过滤与分页。

// 导入
php artisan scout:import "App\Models\Post"

// 查询
$results = Post::search("天气预报")
    ->where("created", ">", strtotime("-30 days"))
    ->paginate(20);

4 高亮与过滤

  • Meilisearch 原始响应里带 _formatted 字段,可在前端直接展示高亮片段。
  • 用 setFilterableAttributes 配置可过滤字段,where 才能生效。
  • 写入或更新模型时 Scout 会自动同步索引,无需手动维护。
T

test1

文章作者

为什么选 Meilisearch Laravel Scout 把“搜索”抽象成模型上的一个可搜索接口,底层可接数据库...

分类
技术
发布时间
2026-10-08
字数
约 1360 字
阅读
3 次