You need to enable JavaScript to run this app. 使用Laravel Scout从MongoDB导入数据到Meilisearch慢且报错如何解决
优惠活动
大模型
产品
解决方案
定价
更多

使用Laravel Scout从MongoDB导入数据到Meilisearch慢且报错如何解决

问题解决步骤

1. 修复Laravel Scout分批导入报错

报错原因是laravel/scout 9.x版本的scout:import命令获取到的-c参数值为字符串类型,传入MongoDB查询的limit参数时未做类型转换,触发MongoDB驱动的类型校验错误。
解决方法:
自定义Artisan导入命令,在分批查询时强制将分批次数值转为整数:

// 新建app/Console/Commands/ScoutImportMongo.php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class ScoutImportMongo extends Command
{
    protected $signature = 'scout:import-mongo {model} {--c|chunk=10000}';
    protected $description = '适配MongoDB的Scout分批导入命令';

    public function handle()
    {
        ini_set('memory_limit', '-1');
        set_time_limit(0);
        
        $model = $this->argument('model');
        $chunkSize = (int)$this->option('chunk');
        
        $model::orderBy('_id')->chunk($chunkSize, function ($records) {
            $records->searchable();
            $this->info('已完成批次导入,当前批次条数:' . $records->count());
        });
        
        $this->info('全部数据导入完成');
    }
}

执行命令改为:php artisan scout:import-mongo 'App\Models\你的模型类名'

2. 修复mongoexport + curl手动导入报错

你遇到两个独立错误:

  1. URL格式错误:路径应为indexes而非indexs,且命令中多了多余的斜杠
  2. JSON格式不符合要求:mongoexport默认输出JSON Lines格式(每行一个JSON对象),Meilisearch要求传入JSON数组
    修复后的操作步骤:
  • 导出时指定jsonArray参数:
    mongoexport --db 你的库名 --collection posts --jsonArray --out /data/posts.json
    如果600万数据导出的单文件过大,可加--limit和--skip参数分批导出分批导入,避免请求超时
  • 执行curl导入:
    curl -X POST 'http://127.0.0.1:7700/indexes/posts/documents' -H "Content-Type: application/json" --data-binary @/data/posts.json

导入速度优化建议

600万量级数据导入可做以下配置提升效率:

  • 导入前临时调整Meilisearch配置:适当调高max-batch-size、max-concurrent-tasks参数,全部数据写入完成后再等待后台构建索引即可
  • MongoDB查询配置无超时游标,避免分批查询过程中MongoDB游标自动过期中断导入

内容的提问来源于stack exchange,提问作者Rhys

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 03:45:03