安装Scout
(1)首先,使用 composer 包管理器来安装 Scout,如果没有安装 composer 包管理器,要先安装;接着进入laravel项目的根目录使用composer 命令安装
```
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"
(4)使用 composer安装scout的es驱动:
composerrequiretamayo/laravel-scout-elastic
(5)安装完驱动之后,修改config\scout.php配合文件,将驱动修改为elasticsearch
'driver'=> env('SCOUT_DRIVER','elasticsearch'),
并在下方添加驱动:
'elasticsearch'=> [//laravel54是项目名,可以自定义'index'=> env('ELASTICSEARCH_INDEX','laravel'),'hosts'=> [ env('ELASTICSEARCH_HOST','http://127.0.0.1:9200'), ], ],
创建command命令
(1)使用php artisan创建command命令
php artisan make:commandESInit
(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];
完成之后使用php artisan命令查看命令是否挂载成功
安装guzzlehttp/guzzle 扩展
composerrequireguzzlehttp/guzzle
配置
(1)修改app\Console\Command\ESInit.php
```public function handle()
{
$client=new Client();
$url=config('scout.elasticsearch.hosts')[0]. '/_template/tmp';
//$client->delete($url);
$param = [
'json'=>[
'template' => config('scout.elasticsearch.index'),
'mappings' => [
'_default_' => [
'dynamic_templates' => [
[
'strings' => [
'match_mapping_type' => 'string',
'mapping' => [
'type' => 'text',
'analyzer' => 'ik_smart',
'fields' => [
'keyword' => [
'type' => 'keyword'
]
]
]
]
]
]
]
],
],
];
$client->put($url,$param);
```
//记录
$this->info("=======创建模板成功=======");
//创建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("=========创建索引成功=========");
}
(2)在我的项目中我使用文章数据表来搜索,因此需要修改post.php,也就是posts数据对于的数据模型
useSearchable;//定义索引里面的type
public function searchableAs(){
return"post";
}
//定义有哪些字段需要搜索
public function toSearchableArray()
{
$position_type=DB::table("class_name")->where('id',$this->position_type)->first();
$education=DB::table('config')->where('id',$this->education)->first();
return [
'position'=>$this->position,
'description'=>$this->description,
'province'=>$this->province,
'position_type'=>@$position_type->name,
'salary'=>$this->min_salary."k-".$this->salary."k",
'education'=>@$education->name,
];
}
导入数据
使用php artisan命令导入数据
php artisan scout:import"\App\Position"
导入成功之后我们在浏览器地址输栏入:127.0.0.1:9200/laravel/position/23(laravel是elasticsearch驱动定义的项目名,position对象的是我项目的position数据模型,23是某条数据的ID )