laravel-elasticsearch 配置以及运用
git:https://github.com/babenkoivan/scout-elasticsearch-driver
composer require babenkoivan/scout-elasticsearch-driver
//在config/app.php最后增加
'providers' => [
Laravel\Scout\ScoutServiceProvider::class,
ScoutElastic\ScoutElasticServiceProvider::class,
]
//执行命令,发布(命令生成elastic配置文件)
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
php artisan vendor:publish --provider="ScoutElastic\ScoutElasticServiceProvider"
//修改elastic配置文件 config/sout.php
'driver' => env('SCOUT_DRIVER', 'elastic'),
添加
'elastic' => [
'index' => env('ELASTICSEARCH_INDEX', 'people'), // people是 ES索引
'hosts' => [
env('ELASTICSEARCH_HOST', 'http://localhost:9200'),
],
],
配置完成开始创建ES 索引 类型
创建索引模板(目录可随意)
php artisan make:index-configurator App\\Es\\PeopleConfigurator
生成文件:
创建索引(指向的是刚刚创建的索引模板):
php artisan elastic:create-index "App\Es\PeopleConfigurator"
创建ES搜索的模型(People是新建的模型名 指向索引模板)
php artisan make:searchable-model People --index-configurator=App\\Es\\PeopleConfigurator
<?php
namespace App;
use App\Es\PeopleConfigurator;
use ScoutElastic\Searchable;
use Illuminate\Database\Eloquent\Model;
class People extends Model
{
use Searchable;
/**
* @var string
*/
protected $indexConfigurator = PeopleConfigurator::class;
/**
* @var array
*/
protected $searchRules = [
//
];
/**
* @var array
*/
protected $mapping = [
'properties' => [ //⽂文档类型设置(相当于mysql的数据类型)
'name' => [
'type' => 'text',// 字段类型为全⽂文检索,如果需要关键字,则修改为keyword,注意keyword字段为整体查询,不不能作为模糊搜索
'analyzer' => 'ik_smart',
'search_analyzer' => 'ik_smart',
'boost' => 5,
'fields' => [
'company_name' => [
'type' => 'keyword',
'ignore_above' => 256,
],
],
],
'city' => [
'type' => 'keyword',
],
'vision' => [
'type' => 'text',
'analyzer' => 'ik_smart',
'search_analyzer' => 'ik_smart',
],
'email' => [
'type' => 'keyword',
],
'phone' => [
'type' => 'keyword',
],
],
];
/**
* 设置索引的type 类似 mysql的表
*
* @return string
*/
public function searchableAs()
{
return 'people';
}
}
更新索引mapp
php artisan elastic:update-mapping "App\Models\Search\People"
//把数据库的数据 插入映射到 elastic服务器上
php artisan scout:import "App\Models\Search\People"
//最后控制器 调用elasticearch的model进行查询
\AppPeople::search('查询的字眼')->get();
php artisan elastic:create-index "App\Es\PeopleConfigurator" // 创建索引
php artisan elastic:update-mapping "App\Models\Search\People" // 更新映射
php artisan scout:import "App\Models\Search\People" // 全量导入数据