最新文章
标签云
网站统计
- 观海听潮•博客
- 81篇
- 151条
- 299207次
- 121次
- 美国弗吉尼亚州
您现在的位置是:首页 > 技术杂谈 > Laravel > php > elasticsearch elasticsearch
1、环境:
laravel5.8 + php 7.13 + mysql5.7
2、安装elasticsearch扩展
在laravel项目的composer.json文件中,在require中添加
"elasticsearch/elasticsearch":"~7.8.0"
然后在终端运行composer update命令。
3、新增配置
打开config/database.php文件,在末端新增配置
'elasticsearch' => [ // Elasticsearch 支持多台服务器负载均衡,因此这里是一个数组 'hosts' => explode(',', env('ES_HOSTS')), ]
在根目录.env文件新增配置(默认端口是9200,可以不填)
ES_HOSTS=http://127.0.0.1:9200
4、初始化elasticsearch对象
将elasticsearch对象注入到laravel容器中
在laravel项目文件app/Providers/AppServiceProvider.php中,新增以下代码
use Elasticsearch\ClientBuilder as ESClientBuilder; public function register() { // 注册一个名为 es 的单例 $this->app->singleton('es', function () { // 从配置文件读取 Elasticsearch 服务器列表 $builder = ESClientBuilder::create()->setHosts(config('database.elasticsearch.hosts')); // 如果是开发环境 if (app()->environment() === 'local') { // 配置日志,Elasticsearch 的请求和返回数据将打印到日志文件中,方便我们调试 $builder->setLogger(app('log')->driver()); } return $builder->build(); }); }
5、测试
在终端运行命令
php artisan tinker
然后输入
>>> app('es')->info()
运行结果:
查看之前创建的文档
>>> app('es')->get(['index' => 'test', 'id' => 1])
运行结果:
查看日志文档
日志中是有请求和返回值的
转载请注明:
观海听潮博客
文章评论

评论列表