Elasticsearch 7.2 在 Laravel 中实践
背景:
最近在laradock中安装了Elasticsearch7.2版本,本来试用elasticquent/Elasticquent 扩展,但是发现其对应的Elasticsearch版本是6.1,而官方推荐的ErickTamayo/laravel-scout-elastic对应的还是5.0版本,所以在github找到babenkoivan/scout-elasticsearch-driver扩展进行Es的实践。
实践
- Elasticsearch-ik中文分词插件安装
安装命令:elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.2.0/elasticsearch-analysis-ik-7.2.0.zip
此处有网友推荐在elasticsearch的dockfile中添加该命令,实操后发现总是安装失败,所以在安装完并启动Elasticsearch容器后,进入该容器执行该命令,安装成功,问题在于重新构建容器后需要再次执行该操作
- babenkoivan/scout-elasticsearch-driver扩展使用
首先按照该扩展的文档进行扩展的引用及相关配置文件的生成:在env中新增SCOUT_DRIVER=elastic
然后执行命令
php artisan make:index-configurator MyIndexConfigurator php artisan make:searchable-model MyModel --index-configurator=MyIndexConfigurator
以上两个命令用于生成模型文件及模型相关配置文件:
$mapping 字段属性的定义需要增加analyzer和search_analyzer两个属性,用于传入ik的分词参数'content' => [ 'type' => 'text', 'analyzer' => 'ik_max_word', 'search_analyzer' => 'ik_smart', ],
最后执行
php artisan elastic:create-index "App\MyIndexConfigurator" php artisan elastic:update-mapping "App\MyModel" php artisan scout:import "App\MyModel"
以上三个命令分别用于创建index,更新对应模型index的mapping,最后导入已有数据到该模型的index 中
- 在模型中调用
App\MyModel::search('phone') ->get();
还有很多模型上的方法及规则可以按情况使用,具体参考文档操作
- 查询已有的index
[GET] http://localhost:9200/model_index
- 查询已有的mapping
[GET] http://localhost:9200/_mapping
- 删除已有的index
[DELETE] http://localhost:9200/model_index
本作品采用《CC 协议》,转载必须注明作者和本文链接