scout 默认不支持 elasticsearch,需安装 spatie/laravel-scout-elasticsearch 扩展;配置 driver 为 elasticsearch,手动创建索引与 mapping,模型需实现 tosearchablearray() 并启用 searchable trait。

Scout 默认驱动不支持 Elasticsearch,必须换扩展
Scout 本身只内置 algolia 和 meilisearch 驱动,elasticsearch 不在官方支持列表里。直接配 SCOUT_DRIVER=elasticsearch 会报 Driver [elasticsearch] not supported 错误。
得装社区维护的扩展包:laravel/scout + tamayo/laravel-scout-elastic(Laravel 8/9)或 algolia/scout-extended(不推荐,它本质还是 Algolia);新项目更建议用 spatie/laravel-scout-elasticsearch,它兼容 Laravel 10+,底层用的是 elasticsearch-php v8。
- 运行
composer require spatie/laravel-scout-elasticsearch - 发布配置:运行
php artisan vendor:publish --provider="Spatie\Searchable\SearchableServiceProvider"(注意不是 Scout 自带的 publish 命令) - 改
config/scout.php的driver为'driver' => 'elasticsearch',并确保elasticsearch配置块存在且指向正确地址(如'hosts' => ['http://localhost:9200'])
模型要加 Searchable trait 且重写 toSearchableArray()
Scout 同步数据靠模型事件触发,但 Elasticsearch 对字段类型敏感,直接同步 $model->toArray() 容易出错:比如日期变字符串、空值被忽略、关联关系没展开。
必须显式控制索引内容。常见错误是漏掉 toSearchableArray(),结果搜 user.name 返回空——因为默认只同步 fillable 字段,而 name 可能是访问器或关联字段。
- 在模型里加
use Searchable;和use SoftDeletes;(如果用了软删,Scout 才能自动清理索引) - 重写
toSearchableArray(),返回你要搜的字段,例如:public function toSearchableArray() { return [ 'id' => $this->id, 'title' => $this->title, 'content' => $this->content, 'author_name' => $this->author->name ?? '', 'published_at' => $this->published_at?->toIso8601String(), ]; } - 别在该方法里调
$this->load(),会 N+1;提前用with()加载好关联,或在搜索前做 join
搜索时不能直接用 search() 返回 Eloquent 集合
Model::search('xxx')->get() 看起来像查数据库,实际发的是 HTTP 请求到 ES,返回的是原始 JSON,再由 Scout 封装成模型实例。但这个过程不走 Eloquent 的 casts、appends 或访问器逻辑,字段值是原始 ES 返回的,可能和数据库不一致。
更麻烦的是分页:ES 的 from/size 分页在深翻时性能差,Scout 默认不做游标分页(searchAfter),paginate(15) 到第 100 页就慢。
- 用
search()后接raw()查看原始响应,确认字段结构:Model::search('test')->raw() - 需要高亮?加
->highlight(['fields' => ['title' => new \stdClass, 'content' => new \stdClass]]),ES 返回的highlight字段不会自动注入模型,得自己取$result['highlight']['title'][0] - 深度分页慎用
paginate();改用cursorPaginate()(需 ES 7.10+,且模型主键必须是数字递增)
索引名和 mapping 必须手动初始化,Scout 不自动建
Scout 不会帮你创建 Elasticsearch index、设置 mapping 或 analyzer。第一次运行 php artisan scout:import 时,如果索引不存在,它只会报错 index_not_found_exception,而不是自动建。
mapping 写错会导致字段无法被分析(比如 text 字段设成 keyword,就搜不出子串),或者聚合失败。ES 7+ 已废弃 type,但 Scout 扩展仍可能默认写 _doc,得检查。
- 先用 curl 手动建索引:
curl -XPUT "http://localhost:9200/posts" -H "Content-Type: application/json" -d '{ "mappings": { "properties": { "title": { "type": "text", "analyzer": "ik_smart" }, "content": { "type": "text", "analyzer": "ik_smart" }, "published_at": { "type": "date" } } } }' - 中文分词要用
ik插件,ES 容器启动时就得挂载插件,光配 analyzer 没用 - 改了 mapping 必须删索引重建(
DELETE /posts),不能热更新字段类型










