Laravel怎么使用Scout全文搜索_Laravel Elasticsearch集成教程【检索】

1次阅读

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

Laravel怎么使用Scout全文搜索_Laravel Elasticsearch集成教程【检索】

Scout 默认驱动不支持 Elasticsearch,必须换扩展

Scout 本身只内置 algoliameilisearch 驱动,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="SpatieSearchableSearchableServiceProvider"(注意不是 Scout 自带的 publish 命令)
  • config/scout.phpdriver'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 的 castsappends 或访问器逻辑,字段值是原始 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),不能热更新字段类型

Elasticsearch 的 mapping 设计和中文分词配置,往往比 Scout 集成本身花的时间还多。别指望跑通 import 就算完事,搜不到结果时,第一反应不该是查 Laravel 日志,而是直接 curl 看 ES 返回了什么。

text=ZqhQzanResources