ping([ 'client' => [ 'timeout' => 5, // 设置请求超时时间 'connect_timeout' => 5 // 设置连接超时时间 ] ]); } catch (\Exception $exception) { // 捕获连接异常并输出错误信息 $this->info($exception->getMessage()); $this->info('无法连接到 Elasticsearch 服务器,请配置 config/elasticsearch.php 文件'); $this->info('默认使用 MySQL 的模糊搜索'); $this->info('配置完毕后可运行: php artisan add:shop-to-search 添加索引'); return; // 退出命令 } // 新建商品索引 if (Product::indexExists()) { // 如果索引已存在,则删除索引 Product::deleteIndex(); $this->info('删除索引'); } // 创建新的索引 Product::createIndex(); $this->info('新建索引成功'); // 开始导入数据 $query = Product::query(); // 创建商品查询 $count = $query->count(); // 获取商品总数 $handle = 0; // 初始化处理计数 // 使用 chunk 方法分批处理商品数据 $query->with('category')->chunk(1000, function (Collection $models) use ($count, &$handle) { // 遍历每个商品模型 $models->map(function (Product $product) use ($count, &$handle) { // 将商品添加到索引 $product->addToIndex($product->getSearchData()); ++$handle; // 处理计数加一 echo "\r {$handle}/$count"; // 输出当前处理进度 }); }); echo PHP_EOL; // 换行 $this->info('索引生成完毕'); // 输出完成信息 } }