Laravel中使用Elasticsearch
安装laravel(暂定项目名lara-es laravel版本5.5下的稳定版)
composer create-project --prefer-dist laravel/laravel lara-es 5.5.*
安装scout
composer require laravel/scout
在config/app.php的
providers
数组中添加(Laravel5.7不需进行此操作)
Laravel\Scout\ScoutServiceProvider::class
执行命令,生成scout的配置文件(在app/config文件夹下生成scout.php)
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
安装laravel-scout-elastic
composer require tamayo/laravel-scout-elastic
composer安装时可能会报错,是版本太高,降低版本
composer require laravel/scout ^5.0.3
在config/app.php的
providers
数组中添加
ScoutEngines\Elasticsearch\ElasticsearchProvider::class
修改scout.php
'driver' => env('SCOUT_DRIVER', 'elasticsearch'),
//配置elasticsearch引擎
'elasticsearch' => [
'index' => env('ELASTICSEARCH_INDEX', 'laravel'),//laravel就是索引的名字,可以随便起
'hosts' => [
env('ELASTICSEARCH_HOST', 'http://127.0.0.1:9200'),
],
]
创建命令
在app\Console\Commands下创建ESinit.php
php artisan make:command ESinit
在app\Console\Kernel.php中
$commands
数组里添加
\App\Console\Commands\ESinit::class
运行命令
composer require guzzlehttp/guzzle
guzzlehttp/guzzle安装成功之后,在ESinit.php文件中的handle()方法添加如下代码
public function handle()
{
$client = new Client();
$url = config('scout.elasticsearch.hosts')[0]. '/inssa';//这里写logstash配置中index参数
$client->delete($url);//检查并删除,如果存在配置会报错
$param = [
'json' => [
'template' => config('scout.elasticsearch.index'),
'mappings' => [
'_default_' => [
'dynamic_templates' => [
[
'string' => [
'match_mapping_type' => 'string',//传进来的是string
'mapping' => [
'type' => 'text',//把传进来的string按text(文本)处理
'analyzer' => 'ik_smart',//用ik_smart进行解析(ik是专门解析中的插件)
'fields' => [
'keywords' => [
'type' => 'keyword'
]
]
]
]
]
]
]
],
],
];
$client->put($url, $param);
$this->info('============create template success============');
//创建index
$url = config('scout.elasticsearch.hosts')[0].'/'.config('scout.elasticsearch.index');
$client->delete($url);//检查并删除,如果存在配置会报错
$param = [
'json' => [
'settings' => [
'refresh_interval' => '5s',
'number_of_shards' => 1,
'number_of_replicas' => 0,
],
'mappings' => [
'_default_' => [
'_all' => [
'enabled' => false
]
]
]
],
];
$client->put($url, $param);
$this->info('==========create index success===========');
}
注意: 运行php artisan es:init命令之前应当先启动elasticsearch,[es环境配
出现如下代表执行成功
============create template success============
==========create index success===========
实例:修改需要搜索的model,以\App\Models\User为例
use Laravel\Scout\Searchable
use Searchable;
public function searchableAs()
{
//此处定义es中的type,可以理解成数据表名
return 'user';
}
public function toSearchableArray()
{
return [
'user_nickname' => $this->nickname,//其中的key值可以自定义,由于多张表字段可能重复,加个前缀如user_
'user_desc' => $this->desc
];
}
php artisan scout:import "\App\Models\User"
$users = User::search($request->input('search'))->get();