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 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。