Laravel Scout 默认不支持 Elasticsearch 6+,因其官方仅内置 Algolia 和数据库全文索引驱动,Elasticsearch 需社区驱动适配;装完 Scout 后必须手动集成兼容客户端(如 elasticsearch/elasticsearch:^6.0)并重写引擎类,否则报 Class not found 或搜索为空。

为什么 Laravel Scout 默认不支持 Elasticsearch 6+?
因为 Laravel 5.5 自带的 Scout 扩展包默认只适配 Algolia 和 MySQL/PostgreSQL 的全文索引,Elasticsearch 需要额外驱动。官方在 6.x 版本才通过 laravel/scout + algolia/algoliasearch-client-php 形成标准链路,而 Elasticsearch 支持被剥离为社区维护——这意味着你装了 scout 并不能直接用 Elasticsearch,必须手动接入兼容驱动。
常见错误现象:Class 'LaravelScoutEnginesElasticsearchEngine' not found 或搜索返回空数组但无报错。
- 确认 Laravel 版本是 5.5.*(非 5.5.0 单点版本,某些 patch 版本对 PSR-4 加载有差异)
- 不要尝试用 Laravel 6+ 的
scout:import命令直接跑在 5.5 上——命令签名和模型绑定逻辑已变更 - 避免使用
elasticquent这类过时包,它依赖elasticsearch-phpv2.x,与 ES 6.x+ 的 REST API 不兼容
用 official/elasticsearch-php 驱动对接 ES 6.x
推荐使用官方客户端 elasticsearch/elasticsearch v6.x 分支(对应 ES 6.8),配合自定义 Scout 引擎。这不是“插件安装完就跑”,而是需要重写引擎类并注册服务。
实操关键点:
- 运行
composer require elasticsearch/elasticsearch:^6.0(注意不是elasticsearch/elasticsearch:7.x,Laravel 5.5 的 Guzzle 版本锁死在 6.x,与 ES 7+ 的 HTTP 客户端冲突) - 新建
app/Scout/ElasticsearchEngine.php,继承LaravelScoutEnginesEngine,重写update()、delete()、search()方法,其中search()必须把 Scout 的where条件转成 ES DSL 查询(例如match_phrase替代模糊匹配) - 在
config/scout.php中设置'driver' => 'elastic',并在AppServiceProvider的boot()中调用Scout::extend('elastic', function ($app) { return new ElasticsearchEngine(/*...*/); });
mapping 设计不当导致搜索无结果
ES 不是数据库,字段类型决定能否被分词、是否参与相关性评分。Laravel 模型字段直接塞进 ES,若未显式声明 text 类型,ES 5/6 默认会设为 keyword,导致 match 查询永远不命中。
典型场景:用户表的 name 字段,在 ES index 中必须设为 {"type": "text", "analyzer": "standard"};而 status 这种枚举值才适合 keyword。
- 建索引前务必执行 PUT 请求定义 mapping,例如:
PUT /users+ body 含"mappings": {"_doc": {"properties": {"name": {"type": "text"}}}} - 不要依赖
auto_mapping——ES 会按首次插入数据推断类型,比如第一次存"123"可能被识别为long,后续字符串就写不进去了 - 更新 mapping 需重建索引,Laravel 中可封装
php artisan scout:flush "App\User"再scout:import,但要注意别漏掉refresh索引别名
中文分词必须单独配置 IK 插件
ES 自带的 standard 分析器对中文是单字切分,搜“苹果手机”会拆成“苹”“果”“手”“机”,无法匹配完整词项。必须装 IK 插件并指定 analyzer。
操作路径:
- ES 服务器执行:
./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.8.2/elasticsearch-analysis-ik-6.8.2.zip(版本必须与 ES 严格一致) - mapping 中将字段设为:
"analyzer": "ik_max_word", "search_analyzer": "ik_smart" - Laravel 模型中,
toSearchableArray()返回的数据无需预处理,分词由 ES 在写入时完成;但查询时需确保search()方法里传的是原始关键词,不要自己做切词
容易忽略的是:IK 插件安装后必须重启 ES 进程,且 curl -XGET localhost:9200/_cat/plugins 要能看到 ik,否则 mapping 创建会失败并静默跳过字段。


















