Laravel 基於 Scout 配置實現 Elasticsearch



一、安裝scout
1、安裝

composer require laravel/scout


2、接下來,你需要將 ScoutServiceProvider 添加到你的 config/app.php 配置文件的 providers 數組中:

Laravel\Scout\ScoutServiceProvider::class,


3、注冊好 Scout 的服務提供者之后,你可以使用 vendor:publish Artisan 命令生成 Scout 的配置文件。這個命令會在你的 config 目錄下生成 scout.php 配置文件:

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

注意:執行上述命令沒反應時 直接執行 php artisan vendor:publish 然后輸入數字選擇

4、使用 composer安裝scout的es驅動:

composer require tamayo/laravel-scout-elastic


5、安裝完驅動之后,修改config\scout.php配合文件,將驅動修改為elasticsearch

'driver' => env('SCOUT_DRIVER', 'elasticsearch'),


6、並在下方添加驅動:

'elasticsearch' => [
//laravel_es_test是項目名,可以自定義
'index' => env('ELASTICSEARCH_INDEX', 'laravel_es_test'),
'hosts' => [
env('ELASTICSEARCH_HOST', 'http://127.0.0.1:9200'),
],
],


二、創建command命令
1、使用php artisan創建command命令

php artisan make:command ESInit


2、執行完命令后會創建app\Console\Command\ESInit.php文件,修改ESInit.php

//使用什么命令啟動腳本
protected $signature = 'es:init';
//描述
protected $description = 'init laravel es for post';


3、在app\Console\Kernel.php中掛載

protected $commands = [
\App\Console\Commands\ESInit::class
];

 

三、配置
1、安裝guzzlehttp/guzzle 擴展

composer require guzzlehttp/guzzle


2、修改app\Console\Command\ESInit.php

/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
try{
//創建template
$client = new \GuzzleHttp\Client(); //這里的Clinet()是你vendor下的GuzzleHttp下的Client文件
$this->createTemplate($client);
$this->info('============create template success============');
$this->createIndex($client);
$this->info('============create index success============');
}catch (\Exception $e){
ownLogs('test.log', $e->getMessage());
}

}

/**
* 創建模板 see https://www.elastic.co/guide/en/elasticsearch/reference/current/dynamic-templates.html
* @param Client $client
*/
private function createTemplate($client)
{
$url = config('scout.elasticsearch.hosts')[0] . '/_template/template_1';
// $client->delete($url);
$client->put($url, [

 
         

'json' => [
'index_patterns' => [config('scout.elasticsearch.index').'*'],
'settings' => [
'number_of_shards' => 1,
],
'mappings' => [
'_source' => [
'enabled' => true
],
'properties' => [
'mapping' => [ // 字段的處理方式
'type' => 'keyword', // 字段類型限定為 string
'fields' => [
'raw' => [
'type' => 'keyword',
'ignore_above' => 256, // 字段是索引時忽略長度超過定義值的字段。
]
],
],
],

 
         

],
],
]);
}

 
         

/**
* 創建索引
* @param Client $client
*/
private function createIndex($client)
{
$url = config('scout.elasticsearch.hosts')[0] . '/' . config('scout.elasticsearch.index');
// $client->delete($url);
$client->put($url, [
'json' => [
'settings' => [
'refresh_interval' => '5s',
'number_of_shards' => 1, // 分片為
'number_of_replicas' => 0, // 副本數
],
],
]);
}

 

 

執行命令

php artisan es:init

 

 

 

注意:當前版本 ES7.3
6.0以下,6.*,7.*,很多語法差別
官方語法地址
https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html

PUT _template/template_1
{
"index_patterns": ["te*", "bar*"],
"settings": {
"number_of_shards": 1
},
"mappings": {
"_source": {
"enabled": false
},
"properties": {
"host_name": {
"type": "keyword"
},
"created_at": {
"type": "date",
"format": "EEE MMM dd HH:mm:ss Z yyyy"
}
}
}
}


四、編輯Model文件,導入數據,調用接口
1、編輯Model文件

<?php

namespace App\Models;

use Laravel\Scout\Searchable;

class User extends Authenticatable
{
use Searchable;

protected $table = 'users';

/**
* The attributes that are mass assignable.
* 可以注入的數據字段
* @var array
*/
protected $fillable = [
'name', 'phone','username'
];

// 定義索引里面的類型
public function searchableAs()
{
return '_doc';
}
// 定義有那些字段需要搜索
public function toSearchableArray()
{
return [
'username' => $this->username,
'phone' => $this->phone,
];
}
}

 


2、導入數據

php artisan scout:import "App\Models\user"

 

 

 

注意:看起來是導入成功其實不一定,
vendor/tamayo/laravel-scout-elastic/src/ElasticsearchEngine.php文件中的update方法
$this->elastic->bulk($params);

這句代碼會最終發送指令到es.但是這里沒接收返回值,建議打印一下

 

 

一次成功,一次未成功

3、調用接口

$q = $request->input('q');
$res = User::search($q)->get();
return Response::success('成功', $res);

 


http://localtest/laravel_es_test/_doc/1
laravel_es_test:索引
_doc:類型
1:id

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM