Elasticsearch 7.2 在 Laravel 中实践

背景:
最近在 laradock 中安装了 Elasticsearch7.2 版本,本来试用 elasticquent/Elasticquent 扩展,但是发现其对应的 Elasticsearch 版本是 6.1,而官方推荐的 ErickTamayo/laravel-scout-elastic 对应的还是 5.0 版本,所以在 github 找到 babenkoivan/scout-elasticsearch-driver 扩展进行 Es 的实践。
实践

  1. 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 容器后,进入该容器执行该命令,安装成功,问题在于重新构建容器后需要再次执行该操作

  2. 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 中

  3. 在模型中调用
    App\MyModel::search('phone') ->get();

    还有很多模型上的方法及规则可以按情况使用,具体参考文档操作

  4. 查询已有的 index
    [GET]    http://localhost:9200/model_index
  5. 查询已有的 mapping
    [GET]   http://localhost:9200/_mapping
  6. 删除已有的 index
    [DELETE]   http://localhost:9200/model_index
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。