You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
aquaculture/app/Console/Commands/AddShopToEsSearchCommand.php

99 lines
3.0 KiB

<?php
namespace App\Console\Commands; // 定义命名空间
use App\Models\Product; // 引入商品模型
use App\Models\SearchAble\ElasticSearchTrait; // 引入 Elasticsearch 特性
use Elasticsearch\ClientBuilder; // 引入 Elasticsearch 客户端构建器
use Illuminate\Console\Command; // 引入 Laravel 命令基类
use Illuminate\Database\Eloquent\Collection; // 引入 Eloquent 集合类
/**
* 将商品添加到 Elasticsearch 搜索的控制台命令
*
* 该命令用于将商品数据添加到 Elasticsearch 的全文索引中。
*/
class AddShopToEsSearchCommand extends Command
{
/**
* 控制台命令的名称和签名
*
* @var string
*/
protected $signature = 'add:shop-to-search';
/**
* 控制台命令的描述
*
* @var string
*/
protected $description = '把商品添加到全文索引';
/**
* 创建一个新的命令实例.
*
* @return void
*/
public function __construct()
{
parent::__construct(); // 调用父类构造函数
}
/**
* 执行控制台命令.
*
* @return mixed
*/
public function handle()
{
try {
// 检查 Elasticsearch 服务器是否可用
ElasticSearchTrait::client()->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('索引生成完毕'); // 输出完成信息
}
}