之前一直直接使用Elasticsearch完成搜索蝴簇,最近發(fā)現(xiàn)了Scout這個Laravel插件,決定試用一下,底層的搜索引擎還是用了Elasticsearch,當然還可以使用Algolia泞莉,主要還有數(shù)據(jù)統(tǒng)計的地方會用到ES,所以底層就都用ES來存儲了船殉。
1. 安裝Elasticsearch
1.1 docker 安裝ES
docker pull docker.elastic.co/elasticsearch/elasticsearch:7.10.0
docker run -d --name elastic -p 9201:9200 -p 9301:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms1g -Xmx1g" docker.io/elasticsearch:7.10.0
1.2 安裝IK分詞
docker exec -it f80b12611cd6 /bin/bash
cd bin
./elasticsearch-plugin -v install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.10.0/elasticsearch-analysis-ik-7.10.0.zip
1.3 重啟docker鏡像
docker restart f80b12611cd6
2. Laravel集成Scout
2.1 安裝依賴
composer require elasticsearch/elasticsearch
composer require tamayo/laravel-scout-elastic:8.0.3 // 因為我的php版本只有7.1
composer require laravel/scout
php artisan vendor:publish
選擇 Laravel\Scout\ScoutServiceProvider
image
2.2 配置參數(shù)
scout.php文件
image
image
3. 搜索內(nèi)容
3.1 更新模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class PlatformItemStock extends Base
{
use Searchable;
protected $table = "platform_item_stock";
public $timestamps = true;
protected $guarded = [];
public function attributes() {
return $this->hasMany(PlatformItemAttribute::class, 'itemsStockId', 'id');
}
public function skuImage()
{
return $this->belongsTo(Attachment::class, 'itemSkuImageId');
}
public function item()
{
return $this->belongsTo(PlatformItem::class, 'itemId');
}
protected function makeAllSearchableUsing($query)
{
return $query->with(['item', 'item.category', 'item.brand', 'item.series', 'item.material']);
}
}
3.2 引入模型內(nèi)容
php artisan scout:import "App\Models\PlatformItemStock"
image
3.3 搜索調(diào)用
public function search($query, $num)
{
return $this->model->search($query)->paginate($num);
}
3.4 更新搜索內(nèi)容
public function store($query)
{
$result = $this->model->create($query);
$result->with(['item', 'item.category', 'item.brand', 'item.series', 'item.material'])->searchable();
return $result;
}
public function update($id, $query)
{
$res = $this->model->find($id);
$res->update($query);
$res->with(['item', 'item.category', 'item.brand', 'item.series', 'item.material'])->searchable();
return $res;
}
ps.臨時修復laravel scout elastic的bug(因為我的docker里面php版本太低了鲫趁,沒辦法升級安裝包,找時間更新一下版本)
打開vendor/tamayo/laravel-scout-elastic/src/Engines/ElasticsearchEngine.php
$result['hits']['total'] = $result['hits']['total']['value'];
// 上面增加這一行
$result['nbPages'] = $result['hits']['total'] / $perPage;
參考:
https://segmentfault.com/a/1190000039854381
https://github.com/medcl/elasticsearch-analysis-ik
https://segmentfault.com/a/1190000021670576
https://cloud.tencent.com/developer/article/1725623
https://github.com/ErickTamayo/laravel-scout-elastic/issues/123