下面给大家介绍在laravel中如何使用elaticsearch(步骤分明),希望对大家有所帮助!
安装相关扩展包
guzzlehttp/guzzle
elasticsearch/elasticsearch
laravel/scout
babenkoivan/scout-elasticsearch-driver
predis/predis 数据量大需要使用队列同步、拉取数据时安装
1、安装 guzzlehttp/guzzle
composerrequireguzzlehttp/guzzle
在 app/Services 目录下编写 Http 服务类
<?phpnamespaceApp\\Services;useGuzzleHttp\\Client;useGuzzleHttp\\Cookie\\CookieJar;classHttpService{protected$client;publicfunction__construct(){$this->client=newClient(['verify'=>false,'timeout'=>0,]);}/***发送get请求*@param$url*@paramarray$aQueryParam*@paramstring$isDecode*@returnmixed*@throws\\GuzzleHttp\\Exception\\GuzzleException*/publicfunctionget($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*@paramarray$aParam*@paramstring$type*@paramstring$isDecode*@returnmixed*@throws\\GuzzleHttp\\Exception\\GuzzleException*/publicfunctionpost($url,$aParam=[],$type='form_params',$isDecode=true){$aOptions=[];//Sendingapplication/x-www-form-urlencodedPOSTif($type=='form_params'){$aOptions['form_params']=$aParam;}//uploadJSONdataif($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*@paramarray$aParam*@paramstring$type*@paramstring$isDecode*@returnmixed*@throws\\GuzzleHttp\\Exception\\GuzzleException*/publicfunctionput($url,$aParam=[],$type='form_params',$isDecode=true){$aOptions=[];//Sendingapplication/x-www-form-urlencodedPOSTif($type=='form_params'){$aOptions['form_params']=$aParam;}//uploadJSONdataif($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*@returnbool|string*/publicfunctiongetRemoteFile($url){$jar=newCookieJar();$aOptions=['cookies'=>$jar];$response=$this->client->request('GET',$url,$aOptions);return$response->getBody()->getContents();}}
2、安装 elasticsearch/elasticsearch
composerrequireelasticsearch/elasticsearch
3、安装 laravel/scout
composerrequirelaravel/scoutphpartisanvendor:publish–provider="Laravel\\Scout\\ScoutServiceProvider"
4、安装 scout 第三方驱动 babenkoivan/scout-elasticsearch-driver
composerrequirebabenkoivan/scout-elasticsearch-driverphpartisanvendor: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/predis
composerrequirepredis/predis
初始化 elatic Template
这里以 artisan 命令的方式配置 生成命令文件
phpartisanmake:commandEsInit<?phpnamespaceApp\\Console\\Commands;useApp\\Services\\HttpService;useIlluminate\\Console\\Command;classEsInitextendsCommand{/***Thenameandsignatureoftheconsolecommand.**@varstring*/protected$signature='es:init';/***Theconsolecommanddescription.**@varstring*/protected$description='initlaravelesforarticle';/***Createanewcommandinstance.**@returnvoid*/protected$http;publicfunction__construct(){parent::__construct();parent::__construct();$this->http=newHttpService();}/***Executetheconsolecommand.**@returnmixed*/publicfunctionhandle(){$this->createTemplate();}protectedfunctioncreateTemplate(){$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-ddHHss','type'=>'date'],'updated_at'=>['format'=>'yy-MM-ddHHss','type'=>'date']]]],];$url=config('scout.elasticsearch.hosts')[0].'/'.'_template/rtf';$this->http->put($url,$aData,'json');}}
生成检索 model
phpartisanmake:modelModels/Article
创建 model 索引配置文件
Elasticsearch\\ArticleIndexConfigurator.php
<?phpnamespaceApp\\Elasticsearch;useScoutElastic\\IndexConfigurator;useScoutElastic\\Migratable;classArticleIndexConfiguratorextendsIndexConfigurator{useMigratable;protected$name='articles';/***@vararray*/protected$settings=['analysis'=>['analyzer'=>['es_std'=>['type'=>'standard','stopwords'=>'_spanish_']]]];}
创建 model 检索规则文件
Elasticsearch\\SearchRules\\ArticleRule.php
<?phpnamespaceApp\\Elasticsearch\\SearchRules;useScoutElastic\\SearchRule;classArticleRuleextendsSearchRule{/**@inheritdoc*/publicfunctionbuildHighlightPayload(){return['fields'=>['title'=>['type'=>'unified',],'content'=>['type'=>'unified',],]];}//进行match搜索,会分词publicfunctionbuildQueryPayload(){$query=$this->builder->query;return['must'=>['query_string'=>['query'=>$query,],],];}}
设置 model Mapping 及检索字段
classArticleextendsModel{protected$indexConfigurator=ArticleIndexConfigurator::class;useSearchable;/***检索规则*@varstring[]*/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*/publicfunctiontoSearchableArray(){return['id'=>$this->id,'title'=>$this->title,'content'=>$this->content,];}}
使用步骤
生成 elatic Template 类似 mysql 表结构
phpartisanes:init
更新 elatic 类型映射
phpartisanelastic:update-mapping"App\\Models\\Article"
数据库数据导入 elatic
phpartisanscout:import"App\\Models\\Article"
PS: 其他命令
清空 elatic 数据
phpartisanscout:flush"App\\Models\\Article"
使用检索
$query=Article::search('二胡')->paginateRaw(3,'article',1);dd($query->items()['hits']);
其他使用请自行查看文档
产品猿社区致力收录更多优质的商业产品,给服务商以及软件采购客户提供更多优质的软件产品,帮助开发者变现来实现多方共赢;
日常运营的过程中我们难免会遇到各种版权纠纷等问题,如果您在社区内发现有您的产品未经您授权而被用户提供下载或使用,您可按照我们投诉流程处理,点我投诉;
本文来自用户发布投稿,不代表产品猿立场 ;若对此文有疑问或内容有严重错误,可联系平台客服反馈;
部分产品是用户投稿,可能本文没有提供官方下下载地址或教程,若您看到的内容没有下载入口,您可以在我们产品园商城搜索看开发者是否有发布商品;若您是开发者,也诚邀您入驻商城平台发布的产品,地址:点我进入;
如若转载,请注明出处:https://www.chanpinyuan.cn/43124.html;