Laravel使用scout集成elasticsearch做全文搜索的实现方法
本文介绍了Laravel使用scout集成elasticsearch做全文搜索的实现方法,分享给大家,具体如下:
安装需要的组件
composerrequiretamayo/laravel-scout-elastic composerrequirelaravel/scout
如果composerrequirelaravel/scout出现报错
Usingversion^6.1forlaravel/scout ./composer.jsonhasbeenupdated Loadingcomposerrepositorieswithpackageinformation Updatingdependencies(includingrequire-dev) Yourrequirementscouldnotberesolvedtoaninstallablesetofpackages. Problem1 -tamayo/laravel-scout-elastic4.0.0requireslaravel/scout^5.0->satisfiablebylaravel/scout[5.0.x-dev]. -tamayo/laravel-scout-elastic4.0.0requireslaravel/scout^5.0->satisfiablebylaravel/scout[5.0.x-dev]. -tamayo/laravel-scout-elastic4.0.0requireslaravel/scout^5.0->satisfiablebylaravel/scout[5.0.x-dev]. -Conclusion:don'tinstalllaravel/scout5.0.x-dev -Installationrequestfortamayo/laravel-scout-elastic^4.0->satisfiablebytamayo/laravel-scout-elastic[4.0.0]. Installationfailed,reverting./composer.jsontoitsoriginalcontent.
那么使用命令
composerrequirelaravel/scout^5.0
修改一下配置文件(config/app.php),添加如下两个provider
'providers'=>[ //essearch加上以下内容 Laravel\Scout\ScoutServiceProvider::class, ScoutEngines\Elasticsearch\ElasticsearchProvider::class, ]
添加完成,执行命令,生成config文件
phpartisanvendor:publish--provider="Laravel\Scout\ScoutServiceProvider"
修改config/scout.php
'driver'=>env('SCOUT_DRIVER','elasticsearch'), 'elasticsearch'=>[ 'index'=>env('ELASTICSEARCH_INDEX','你的Index名字'), 'hosts'=>[ env('ELASTICSEARCH_HOST',''), ], ],
在.env配置ES的账号:密码@连接
ELASTICSEARCH_HOST=elastic:密码@你的域名.com:9200
创建一个生成mapping的命令行文件,到app/Console/Commands
['elastic','Wangcai5388']]); $url=config('scout.elasticsearch.hosts')[0].'/_template/news'; $params=[ 'json'=>[ 'template'=>config('scout.elasticsearch.index'), 'settings'=>[ 'number_of_shards'=>5 ], 'mappings'=>[ '_default_'=>[ 'dynamic_templates'=>[ [ 'strings'=>[ 'match_mapping_type'=>'string', 'mapping'=>[ 'type'=>'text', 'analyzer'=>'ik_smart', 'ignore_above'=>256, 'fields'=>[ 'keyword'=>[ 'type'=>'keyword' ] ] ] ] ] ] ] ] ] ]; $client->put($url,$params); //创建index $url=config('scout.elasticsearch.hosts')[0].'/'.config('scout.elasticsearch.index'); $params=[ 'json'=>[ 'settings'=>[ 'refresh_interval'=>'5s', 'number_of_shards'=>5, 'number_of_replicas'=>0 ], 'mappings'=>[ '_default_'=>[ '_all'=>[ 'enabled'=>false ] ] ] ] ]; $client->put($url,$params); } }
在kernel中注册这个命令
执行这个命令生成mapping
phpartisanes:init修改model支持全文搜索
hasOne(Star::class,'id','star_id'); } publicfunctioncategory() { return$this->hasOne(Category::class,'id','category_id'); } publicstaticfunctiongetActivityIdByName($name) { returnself::select('id') ->where([ ['status','=',1], ['type_id','=',2], ['title','like','%'.$name.'%'] ])->get()->pluck('id'); } }导入全文索引信息
phpartisanscout:import"App\ActivityNews\Model\ActivityNews"测试简单的全文索引
phpartisantinker >>>App\ActivityNews\Model\ActivityNews::search('略懂皮毛')->get();以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。