composer require laravel/scout
Laravel\Scout\ScoutServiceProvider::class,
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
注意:执行上述命令没反应时 直接执行 php artisan vendor:publish 然后输入数字选择
4、使用 composer安装scout的es驱动:
composer require tamayo/laravel-scout-elastic
'driver' => env('SCOUT_DRIVER', 'elasticsearch'),
'elasticsearch' => [//laravel_es_test是项目名,可以自定义'index' => env('ELASTICSEARCH_INDEX', 'laravel_es_test'),'hosts' => [env('ELASTICSEARCH_HOST', 'http://127.0.0.1:9200'),],],
php artisan make:command ESInit
//使用什么命令启动脚本protected $signature = 'es:init';//描述protected $description = 'init laravel es for post';
protected $commands = [\App\Console\Commands\ESInit::class];
三、配置
1、安装guzzlehttp/guzzle 扩展composer require guzzlehttp/guzzle
/*** 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.htmlPUT _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"}}}}
$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/1laravel_es_test:索引_doc:类型 1:id