1. 準(zhǔn)備工作
因?yàn)槲冶镜豴hp版本是7.3.4,不支持太高的es。
所以使用如下環(huán)境:
laravel6 + php7.3.4 + elastic search 7.17.2
2. 本地安裝elastic search
1. 下載安裝包(這里下載的是7.17.2版本) https://www.elastic.co/cn/downloads/past-releases
2. 解壓進(jìn)入文件夾
3. 修改config/jvm.options文件,
1. 將虛擬機(jī)大小
-Xms4g
-Xmx4g
改為:
-Xms256m
-Xmx1g
2. 再文件最后添加以下代碼。(防止啟動(dòng)時(shí)亂碼)
-Dfile.encoding=GBK
4. 雙擊bin目錄下的elasticsearch.bat文件,啟動(dòng)elastic search。
5. 訪問http://localhost:9200/ 即可安裝成功。
注意事項(xiàng):
- 如果是8以上版本,初次啟動(dòng)時(shí)會(huì)生成密碼。安裝成功以后,訪問https://localhost:9200/,會(huì)提示輸入密碼。用戶名為elastic,密碼就是初始化時(shí)的密碼。
- 如果是8以上版本,初始化以后,攜帶密碼訪問的話,需要訪問
https
,而不是http
。- 如果是8以上版本,想要關(guān)閉密碼的話,需要修改config/elasticsearch.yml文件,修改如下:
xpack.security.enabled: false
3. laravel安裝es依賴
composer require elasticsearch/elasticsearch “7.17.2”
配置database.php
'elasticsearch' => [
// Elasticsearch 支持多臺(tái)服務(wù)器負(fù)載均衡,因此這里是一個(gè)數(shù)組
'hosts' => explode(',',env('ES_HOSTS')),
]
.env 配置
ES_HOSTS=127.0.0.1:9200
初始化es對象,注入到容器中。
修改App/Providers/AppServiceProvider.php文件
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Elasticsearch\ClientBuilder as ESClientBuilder;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
// 注冊一個(gè)名為 es 的單例
$this->app->singleton('es', function () {
// 從配置文件讀取 Elasticsearch 服務(wù)器列表
$builder = ESClientBuilder::create()->setHosts(config('database.elasticsearch.hosts'));
// 如果是開發(fā)環(huán)境
if (app()->environment() === 'local') {
// 配置日志,Elasticsearch 的請求和返回?cái)?shù)據(jù)將打印到日志文件中,方便我們調(diào)試
$builder->setLogger(app('log')->driver());
}
return $builder->build();
});
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
}
測試是否成功,
php artisan tinker
>>>app('es')->info();
會(huì)輸出和訪問http://127.0.0.1:9200
一樣的內(nèi)容。
4. laravel中使用es
創(chuàng)建腳本代碼
php artisan make:command Elasticsearch/SyncProducts
修改app/Console/Commands/Elasticsearch/SyncProducts.php
文件
<?php
namespace App\Console\Commands\Elasticsearch;
use App\Models\Product;
use Illuminate\Console\Command;
class SyncProducts extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'es:sync-products';
/**
* The console command description.
*
* @var string
*/
protected $description = '將商品數(shù)據(jù)同步到 Elastic Search';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// 獲取 Elasticsearch 對象
$es = app('es');
$sql = 'id,`name`,`desc`,brand_id,category_id,shop_id,price,sold_count,review_count,status,create_time';
Product::query()
->selectRaw($sql)
// 使用 chunkById 避免一次性加載過多數(shù)據(jù)
->chunkById(100, function ($products) use ($es) {
$this->info(sprintf('正在同步 ID 范圍為 %s 至 %s 的商品', $products->first()->id, $products->last()->id));
// 初始化請求體
$req = ['body' => []];
// 遍歷商品
foreach ($products as $product) {
// 將商品模型轉(zhuǎn)為 Elasticsearch 所用的數(shù)組
$data = $product->toESArray($product->id, $product->category_id);
$req['body'][] = [
'index' => [
'_index' => 'test',
'_id' => $data['id'],
],
];
$req['body'][] = $data;
}
try {
// 使用 bulk 方法批量創(chuàng)建
$es->bulk($req);
} catch (\Exception $e) {
$this->info($e->getMessage());
}
});
$this->info('同步完成');
}
}
創(chuàng)建Product模型進(jìn)行數(shù)據(jù)過濾
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
class Product extends Model
{
//
public $table = "product";
public function toESArray($product_id,$category_id)
{
// 只取出需要的字段
$arr = Arr::only($this->toArray(), [
'id',
'name',
'desc',
'brand_id',
'shop_id',
'price',
'sold_count',
'review_count',
'status',
'create_time'
]);
// $productSkus = ProductSkus::query()->selectRaw('name,price')->where('product_id',$product_id)->get()->toArray();
// skus在索引中是一個(gè)二維數(shù)組, 這里只取出需要的 SKU 字段
// $arr['skus'] = $productSkus;
$arr['skus'] = rand(111111,999999);
// $sql = "lmrs_at.name as name,lmrs_at_val.name as value";
// $attributes = Attributes::query()->selectRaw($sql)
// ->from('attributes as at')
//
// ->leftJoin('attribute_values as at_val','at.id','at_val.attribute_id')
//
// ->where('at.category_id',$category_id)
//
// ->get()->toArray();
// attributes 在索引中是一個(gè)二維數(shù)組, 這里只取出需要的商品屬性字段
// $arr['attributes'] = $attributes;
$arr['attributes'] = 'attributes';
return $arr;
}
}
我們在寫入商品數(shù)據(jù)的時(shí)候用的是 bulk() 方法,這是 Elasticsearch 提供的一個(gè)批量操作接口。設(shè)想一下假如我們系統(tǒng)里有數(shù)百萬條商品,如果每條商品都單獨(dú)請求一次 Elasticsearch 的 API,那就是數(shù)百萬次的請求,性能肯定是很差的,而 bulk() 方法可以讓我們用一次 API 請求完成一批操作,從而減少請求次數(shù)的數(shù)量級,提高整體性能。
創(chuàng)建表
CREATE TABLE `zlsn_product` (
`id` int(4) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL COMMENT '商品名',
`desc` varchar(255) DEFAULT NULL COMMENT '描述',
`brand_id` int(4) DEFAULT NULL COMMENT '品牌id',
`category_id` int(4) DEFAULT NULL COMMENT '分類id',
`shop_id` int(4) DEFAULT NULL COMMENT '店鋪id',
`price` decimal(10,2) DEFAULT NULL COMMENT '價(jià)格',
`sold_count` int(4) DEFAULT NULL COMMENT '賣出數(shù)量',
`review_count` int(4) DEFAULT NULL COMMENT '回購數(shù)量',
`status` tinyint(1) DEFAULT '1' COMMENT '狀態(tài) 1 正常 2 下架',
`create_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1002 DEFAULT CHARSET=utf8mb4 COMMENT='商品表';
創(chuàng)建執(zhí)行過程,用來隨機(jī)插入1000條測試數(shù)據(jù)
CREATE PROCEDURE p01 ()
BEGIN
declare i int;
set i=1001;
while i<=2000 do
INSERT INTO product ( `name`, `desc`, brand_id, category_id, shop_id, price, sold_count, review_count, `status`, create_time )
VALUES
(
(SELECT
SUBSTRING( MD5( RAND()), 1, 5 )),
(SELECT
SUBSTRING( MD5( RAND()), 1, 10 )),
(SELECT
CEILING( RAND() * 1000 )),
(SELECT
CEILING( RAND() * 1000 )),
(SELECT
CEILING( RAND() * 1000 )),
(SELECT
CEILING( RAND() * 1000 )),
(SELECT
CEILING( RAND() * 1000 )),
(SELECT
CEILING( RAND() * 1000 )),
1,
NOW());
set i=i+1;
end WHILE;
END;
運(yùn)行以下SQL,執(zhí)行此執(zhí)行過程,生成測試數(shù)據(jù)
CALL p01 ();
此時(shí)zlsn_product表中就有測試數(shù)據(jù)了。文章來源:http://www.zghlxwxcb.cn/news/detail-503525.html
運(yùn)行php腳本,將生成的SQL數(shù)據(jù)存入到es文章來源地址http://www.zghlxwxcb.cn/news/detail-503525.html
php artisan es:sync-products
參考鏈接
- laravel使用elasticsearch
- Mysql循環(huán)添加1000條數(shù)據(jù)案列
- MySQL生成隨機(jī)字符串
- win10下Elasticsearch安裝配置完整教程
到了這里,關(guān)于關(guān)于laravel使用Elastic Search的一些記錄的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!