elasticsearch搜索商品

使用Elasticsearch完成商品搜索

最近开发的项目需要收集商品信息,顾名思义,又是一个搜索巨多的活,果断上ES。

一. 安装扩展

首先,通过 Composer 包管理器来安装 Scout:

 composer require laravel/scout

这是官方的扩展,这个驱动对我们来说不太友好,我需要别的驱动,我选择 scout-elasticsearch-driver

composer require babenkoivan/scout-elasticsearch-driver

如果您使用的是 Laravel 版本 <= 5.4,请在 config/app.php 中添加以下

'providers' => [
    Laravel\Scout\ScoutServiceProvider::class,
    ScoutElastic\ScoutElasticServiceProvider::class,
]

全部安装完成后,使用命令来生成 Scout 配置文件。这个命令将在你的 config 目录下生成 scout.php 以及scout_elastic.php 配置文件。

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
php artisan vendor:publish --provider="ScoutElastic\ScoutElasticServiceProvider"

二. es配置

.env 文件添加

// 驱动的host信息,如果有账号密码:http://elastic_user:password@127.0.0.1:9200
SCOUT_ELASTIC_HOST=elasticsearch:9200
// 驱动
SCOUT_DRIVER=elastic
// 是否开启队列,默认不需要配置,建议开启
SCOUT_QUEUE=true

三. 索引配置

索引配置器用于为 Elasticsearch 设置索引。这里我需要一个商品的索引,请使用以下 artisan 命令:

php artisan elastic:create-index  "App\Elasticsearch\IndexConfigurators\ProductIndexConfigurator"

执行成功后需要配置商品的索引

<?php

namespace App\Elasticsearch\IndexConfigurators;

use ScoutElastic\IndexConfigurator;
use ScoutElastic\Migratable;

class ProductIndexConfigurator extends IndexConfigurator
{
    use Migratable;

    protected $name = 'product_index';

    // You can specify any settings you want, for example, analyzers.
    protected $settings = [
        'number_of_shards' => 5,
        'number_of_replicas' => 0,
        'max_result_window' => 100000000
    ];

    protected $defaultMapping = [
        'properties' => [
            'id' => [
                'type' => 'integer',
            ],
            'title' => [
                'type' => 'text',
                'analyzer' => 'ik_max_word',
                'search_analyzer' => 'ik_smart',
            ],
            'desc' => [
                'type' => 'text',
                'analyzer' => 'ik_max_word',
                'search_analyzer' => 'ik_smart'
            ],
            'created_at' => [
                'type' => 'date',
                'format' => 'yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis'
            ]
        ],
    ];
}

我就简单的配置了一点,上面我用到中文分词,这里就不阐述怎么安装ik了,具体的根据自己的字段来选择合适的类型。然后在商品的模型:

<?php
namespace App\Models;

use App\Elasticsearch\IndexConfigurators\ProductIndexConfigurator;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use ScoutElastic\Searchable;

class Product extends Model
{
    use HasFactory,
        Searchable;

    protected $indexConfigurator = ProductIndexConfigurator::class;

    public function toSearchableArray() {
      return [
         'id' => $this->id,
         'title' => $this->title,
         'desc' => $this->desc,
         'created_at' => $this->created_at
      ]
    }

}

在模型中设置映射后,可以更新 Elasticsearch 类型映射,也就是把我们刚才创建的索引和商品的模型绑定在一起。

 php artisan elastic:update-mapping "App\Models\Product"

你也可以把数据库的数据导入到Elasticsearch中,具体的使用方法还是去看看这两个扩展的详细文档。

php artisan scout:import "App\Models\Product"

到这里基本都成了,嘿嘿。

四. 搜索使用

这个扩展的好处就是基本上的搜索还是和LaravelORM一致,会少一点,具体的还是自己去看文档

        Product::search('phone')
            // specify columns to select
            ->select(['title', 'price'])
            // filter 
            ->where('color', 'red')
            // sort
            ->orderBy('price', 'asc')
            // collapse by field
            ->collapse('brand')
            // set offset
            ->from(0)
            // set limit
            ->take(10)
            // get results
            ->get();

结语

感谢一下扩展的优秀作者,才能让我们好好偷懒,感谢!

本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由系统于 2年前 自动加精
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 23

数据新增或者修改之后用这个包,es中怎么同步呢

2年前 评论

@风吹过有夏天的味道 基本上的增删改查会自动同步,Scout 全文搜索《Laravel 8 中文文档》

2年前 评论
风吹过有夏天的味道 2年前
changebeizhanyong 2年前
luyang (作者) (楼主) 2年前
changebeizhanyong 2年前
changebeizhanyong 2年前
luyang (作者) (楼主) 2年前

..还是想问下 ik 分词器怎么装

2年前 评论
风吹过有夏天的味道 2年前
luyang (楼主) 2年前
laravelphp_game (作者) 2年前

可以像阿里云open search一样做作数据上报给商品个性化搜索吗

2年前 评论
luyang (楼主) 2年前
chowjiawei

你的头像真好看,之前是往上冲的,现在是横着飞的,这个叫什么啊,我也想拥有

2年前 评论
chowjiawei (作者) 2年前
luyang (楼主) 2年前

确实不错,不用考虑 laravel 版本的问题,而 laravel/scoutlaravel5.7 版本上就困扰了好几天

2年前 评论

file 你好,我到了批量导入数据的时候 会提示这个报错,是什么原因呢。。 一下午了,还没有解决。。 laravel 版本9 es版本8.4.1 分词器什么的都装好了,就差这一步了

1年前 评论
luyang (楼主) 1年前
on_the_way_liuda (作者) 1年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!