下面由laravel教程栏目带大家介绍在laravel中如何使用elaticsearch(步骤分明),希望对大家有所帮助!
安装相关扩展包
guzzlehttp/guzzleelasticsearch/elasticsearchlaravel/scoutbabenkoivan/scout-elasticsearch-driverpredis/predis 数据量大需要使用队列同步、拉取数据时安装1.安装 guzzlehttp/guzzlecomposer require guzzlehttp/guzzle
在 app/services 目录下编写 http 服务类<?phpnamespace app\services;use guzzlehttp\client;use guzzlehttp\cookie\cookiejar;class httpservice{ protected $client; public function __construct() { $this->client = new client(['verify' => false, 'timeout' => 0,]); } /** * 发送 get 请求 * @param $url * @param array $aqueryparam * @param string $isdecode * [@return](https://learnku.com/users/31554) mixed * @throws \guzzlehttp\exception\guzzleexception */ public function get($url, $aqueryparam = [], $isdecode = true) { $response = $this->client->request('get', $url, [ 'query' => $aqueryparam ]); if($isdecode){ return \guzzlehttp\json_decode($response->getbody()->getcontents(), true); } return $response->getbody()->getcontents(); } /** * 发送 post 请求 * @param $url * @param array $aparam * @param string $type * @param string $isdecode * [@return](https://learnku.com/users/31554) mixed * @throws \guzzlehttp\exception\guzzleexception */ public function post($url, $aparam = [], $type = 'form_params', $isdecode = true) { $aoptions = []; // sending application/x-www-form-urlencoded post if ($type == 'form_params') { $aoptions['form_params'] = $aparam; } // upload json data if ($type == 'json') { $aoptions['json'] = $aparam; } $response = $this->client->request('post', $url, $aoptions); if($isdecode){ return \guzzlehttp\json_decode($response->getbody()->getcontents(), true); } return $response->getbody()->getcontents(); } /** * 发送 put 请求 * @param $url * @param array $aparam * @param string $type * @param string $isdecode * [@return](https://learnku.com/users/31554) mixed * @throws \guzzlehttp\exception\guzzleexception */ public function put($url, $aparam = [], $type = 'form_params', $isdecode = true) { $aoptions = []; // sending application/x-www-form-urlencoded post if ($type == 'form_params') { $aoptions['form_params'] = $aparam; } // upload json data if ($type == 'json') { $aoptions['json'] = $aparam; } $response = $this->client->request('put', $url, $aoptions); if($isdecode){ return \guzzlehttp\json_decode($response->getbody()->getcontents(), true); } return $response->getbody()->getcontents(); } /** * 保存远程文件到本地 * 跟随第三方服务器url重定向 * @param $url * [@return](https://learnku.com/users/31554) bool|string */ public function getremotefile($url) { $jar = new cookiejar(); $aoptions = ['cookies' => $jar]; $response = $this->client->request('get', $url, $aoptions); return $response->getbody()->getcontents(); }}
2.安装 elasticsearch/elasticsearchcomposer require elasticsearch/elasticsearch
3.安装 laravel/scoutcomposer require laravel/scoutphp artisan vendor:publish --provider=laravel\scout\scoutserviceprovider
4.安装 scout 第三方驱动 babenkoivan/scout-elasticsearch-drivercomposer require babenkoivan/scout-elasticsearch-driverphp artisan vendor:publish --provider=scoutelastic\scoutelasticserviceprovider
scout 服务配置,在 env 中增加配置项
// 驱动的host,若需账密:http://es_username:password@127.0.0.1:9200scout_elastic_host=elasticsearch:9200// 驱动scout_driver=elastic// 队列配置,数据量大时建议开启scout_queue=true
5.安装 predis/prediscomposer require predis/predis
初始化 elatic template这里以 artisan 命令的方式配置 生成命令文件
php artisan make:command esinit
<?phpnamespace app\console\commands;use app\services\httpservice;use illuminate\console\command;class esinit extends command{ /** * the name and signature of the console command. * * @var string */ protected $signature = 'es:init'; /** * the console command description. * * @var string */ protected $description = 'init laravel es for article'; /** * create a new command instance. * * [@return](https://learnku.com/users/31554) void */ protected $http; public function __construct() { parent::__construct(); parent::__construct(); $this->http = new httpservice(); } /** * execute the console command. * * [@return](https://learnku.com/users/31554) mixed */ public function handle() { $this->createtemplate(); } protected function createtemplate() { $adata = [ /* * 这句是取在scout.php(scout是驱动)里我们配置好elasticsearch引擎的index项。 * ps:其实都是取数组项,scout本身就是return一个数组, * scout.elasticsearch.index就是取 * scout[elasticsearch][index] * */ 'template'=>config('scout.elasticsearch.index'), 'mappings'=>[ 'articles' => [ 'properties' => [ 'title' => [ 'type' => 'text' ], 'content' => [ 'type' => 'text' ], 'created_at' => [ 'format' => 'yy-mm-dd hhss', 'type' => 'date' ], 'updated_at' => [ 'format' => 'yy-mm-dd hhss', 'type' => 'date' ] ] ] ], ]; $url = config('scout.elasticsearch.hosts')[0] . '/' . '_template/rtf'; $this->http->put($url,$adata,'json'); }}
生成检索 modelphp artisan make:model models/article
创建 model 索引配置文件elasticsearch\articleindexconfigurator.php<?phpnamespace app\elasticsearch;use scoutelastic\indexconfigurator;use scoutelastic\migratable;class articleindexconfigurator extends indexconfigurator{ use migratable; protected $name = 'articles'; /** * @var array */ protected $settings = [ 'analysis' => [ 'analyzer' => [ 'es_std' => [ 'type' => 'standard', 'stopwords' => '_spanish_' ] ] ] ];}
创建 model 检索规则文件elasticsearch\searchrules\articlerule.php
<?phpnamespace app\elasticsearch\searchrules;use scoutelastic\searchrule;class articlerule extends searchrule{ /* * @inheritdoc */ public function buildhighlightpayload() { return [ 'fields' => [ 'title' => [ 'type' => 'unified', ], 'content' => [ 'type' => 'unified', ], ] ]; } //进行 match 搜索,会分词 public function buildquerypayload() { $query = $this->builder->query; return [ 'must' => [ 'query_string' => [ 'query' => $query, ], ], ]; }}
设置 model mapping 及检索字段class article extends model{ protected $indexconfigurator = articleindexconfigurator::class; use searchable; /** * 检索规则 * @var string[] */ protected $searchrules = [ articlerule::class ]; // 设置模型字段的映射关系 protected $mapping = [ 'properties' => [ 'id' => [ 'type' => 'integer', ], 'title' => [ 'type' => 'text', 'analyzer' => 'ik_max_word', 'search_analyzer' => 'ik_max_word', 'index_options' => 'offsets', 'store' => true ], 'content' => [ 'type' => 'text', 'analyzer' => 'ik_max_word', 'search_analyzer' => 'ik_max_word', 'index_options' => 'offsets', 'store' => true ], 'number' => [ 'type' => 'integer', ], ], ]; /** * 设置 es 检索返回的字段 * [@return](https://learnku.com/users/31554) array */ public function tosearchablearray() { return [ 'id' => $this->id, 'title' => $this->title, 'content' => $this->content, ]; }}
使用步骤生成 elatic template 类似 mysql 表结构
php artisan es:init
更新 elatic 类型映射
php artisan elastic:update-mapping app\models\article
数据库数据导入 elatic
php artisan scout:import app\models\article
ps: 其他命令
清空 elatic 数据
php artisan scout:flush app\models\article
使用检索 $query = article::search('二胡') ->paginateraw(3,'article',1); dd($query->items()['hits']);
其他使用请自行查看文档以上就是教你在laravel中如何使用elaticsearch(步骤分明)的详细内容。