当前位置: 首页 > 后端技术 > PHP

es-for-Laravel:Composer包安装,Laravel运行Elasticsearch最简单的方法

时间:2023-03-29 14:39:59 PHP

Composer安装:composerrequireethansmart/es-for-laravelgithub地址:https://github.com/roancsu/es-for-laravelESforLaravelUsageEsBuilder有两种模式ESORMClient(ORM模式):支持模型映射ESClient(非-ORM模式):支持原生ES使用ESORMClient先创建ORM模型useEthansmart\EsBuilder\Model\EsModel;/***ClassAtPerson*$hostESIP或URL地址*$portES端口*$indexES索引名*$typeES索引类型名称*@packageEthan\EsBuilder\Model*/classAtPersonextendsEsModel{protected$host="127.0.0.1";受保护的$port="32800";受保护的$index="账户";protected$type="person";}然后使用Model在ES上进行CURD操作搜索try{$result=AtPerson::build()->select("user")->where("user",'=='"chengluo")->where("title,desc","like","AI")->where("create_time","<","2018-10-05")->get();}catch(\Exception$e){return['code'=>-1,'msg'=>$e->getMessage()];}return$result;添加try{$id=5;$数据=['id'=>$id,'params'=>['user'=>'EthanCheng','title'=>'AI'.str_random(8),'desc'=>'AI'.str_random(12)]];$result=AtPerson::build()->create($data);}catch(\Exception$e){return['code'=>-1,'msg'=>$e->getMessage()];}return$result;更新try{$id=5;$data=['id'=>$id,'params'=>['user'=>'EthanCheng','title'=>'AI'.str_random(8),'desc'=>'AI'.str_random(12)]];$result=AtPerson::build()->update($data);}catch(\Exception$e){return['code'=>-1,'msg'=>$e->getMessage()];}return$result;删除try{$id=5;$result=AtPerson::build()->delete($id);}catch(\Exception$e){throw$e;}return$result;使用ESClient首先构建Clientprivate$client;publicfunction__construct(){$host="127.0.0.1";$端口=“32800”;$this->client=EsClientBuilder::create()->setHosts($host)->setPort($port)->build();}调用Client中的方法对ES进行CURD操作$data=['index'=>'accounts','type'=>'person','body'=>["query"=>["bool"=>["must"=>["match"=>["user"=>"ethan"]]]]],];尝试{$result=$this->client->search($data);}catch(\Exception$e){return['code'=>-1,'msg'=>$e->getMessage()];}返回$结果;其他方法类似于创建LaravelJob同步数据到ESuseEthansmart\EsBuilder\Builder\EsClientBuilder;classEsService{private$client;公共函数__construct(){$host="127.0.0.1";$端口=“32800”;$this->client=EsClientBuilder::create()->setHosts($host)->setPort($port)->build();}公共函数创建($id){$data=['index'=>'accounts','type'=>'person','id'=>$id,'body'=>['user'=>str_random(6),'title'=>str_random(12),'desc'=>str_random(16),]];尝试{$result=$this->client->create($data);}catch(\Exception$e){return['code'=>-1,'msg'=>$e->getMessage()];}返回$结果;}}Q??:在使用composer安装过程中,出现以下异常:[InvalidArgumentException]Couldnotfindaversionofpackageethansmart/es-for-laravelmatchingyourminimum-stability(stable).要求它具有明确的版本约束,以实现其所需的稳定性。解决方法:在项目中添加composer.json文件:"repositories":[{"packagist.org":false},{"type":"composer","url":"https://packagist.org"}],把国内的composer镜像换成packagist.org就好了。