头图
在我的mall电商实战项目中,有使用过Elasticsearch实现商品搜索功能。其实商品搜索也可以使用Meilisearch来实现,实现起来还是非常方便的,今天就来带大家实现一下!

前置知识

学习本文需要对Meilisearch有所了解,还没有了解过它的小伙伴可以参考下这篇教程:

《超越Elasticsearch!号称下一代搜索引擎,性能炸裂!》

下面是使用Meilisearch实现商品搜索的效果图,搜索速度还是非常快的!

mall项目

由于我们会以mall项目中的商品搜索功能为例来讲解Meilisearch的使用,这里先简单介绍下mall项目。

mall项目是一套基于 SpringBoot3 + Vue 的电商系统(Github标星60K),后端支持多模块和2024最新微服务架构,采用Docker和K8S部署。包括前台商城项目和后台管理系统,能支持完整的订单流程!涵盖商品、订单、购物车、权限、优惠券、会员、支付等功能!

项目演示:

实现商品搜索

接下来就来带大家使用SpringBoot + Meilisearch实现下商品搜索功能。
  • 首先我们需要在项目的pom.xml文件中添加Meilisearch的Java SDK依赖;
<!--Meilisearch Java SDK-->
<dependency>
    <groupId>com.meilisearch.sdk</groupId>
    <artifactId>meilisearch-java</artifactId>
    <version>0.14.3</version>
</dependency>
  • 然后在application.yml文件中添加Meilisearch的连接配置;
meilisearch:
  host: http://192.168.3.101:7700
  index: products
  • 然后添加Java配置类MeilisearchConfig,配置好Meilisearch对应的Client;
/**
 * @auther macrozheng
 * @description Meilisearch配置类
 * @date 2025/4/18
 * @github https://github.com/macrozheng
 */
@Configuration
public class MeilisearchConfig {

    @Value("${meilisearch.host}")
    private String MEILISEARCH_HOST;

    @Bean
    public Client searchClient(){
        return new Client(new Config(MEILISEARCH_HOST,null));
    }
}
  • 之后创建一个Controller,在其中注入Meilisearch的index,然后通过Client的index方法创建商品的索引并导入文档;
/**
 * @auther macrozheng
 * @description Meilisearch搜索功能Controller
 * @date 2025/4/18
 * @github https://github.com/macrozheng
 */
@RestController
@Tag(name = "MeilisearchController",description = "Meilisearch搜索功能")
@RequestMapping("/meilisearch")
public class MeilisearchController {

    @Value("${meilisearch.index}")
    private String MEILISEARCH_INDEX;

    @Autowired
    private Client searchClient;

    @Operation(summary = "创建索引并导入商品数据")
    @GetMapping("/createIndex")
    public CommonResult createIndex(){
        ClassPathResource resource = new ClassPathResource("json/products.json");
        String jsonStr = IoUtil.read(resource.getStream(), Charset.forName("UTF-8"));
        Index index = searchClient.index(MEILISEARCH_INDEX);
        TaskInfo info = index.addDocuments(jsonStr, "id");
        return CommonResult.success(info);
    }

    @Operation(summary = "刪除商品索引")
    @GetMapping("/deleteIndex")
    public CommonResult deleteIndex(){
        TaskInfo info = searchClient.deleteIndex(MEILISEARCH_INDEX);
        return CommonResult.success(info);
    }
}
  • 这里为了方便测试,我把商品数据存放到了JSON文件中,商品数据具体结构如下;
{
    "id": 27,
    "productSn": "7437788",
    "brandId": 6,
    "brandName": "小米",
    "productCategoryId": 19,
    "productCategoryName": "手机通讯",
    "pic": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/20180615/xiaomi.jpg",
    "name": "小米8 全面屏游戏智能手机 6GB+64GB 黑色 全网通4G 双卡双待",
    "subTitle": "骁龙845处理器,红外人脸解锁,AI变焦双摄,AI语音助手小米6X低至1299,点击抢购",
    "keywords": "",
    "price": 2699.0,
    "sale": 99,
    "newStatus": 1,
    "recommandStatus": 1,
    "stock": 100,
    "promotionType": 3,
    "sort": 0
}
  • 由于我们需要实现在搜索时对商品分类的筛选和商品价格的排序,这里还需要修改下商品的索引设置;
/**
 * @auther macrozheng
 * @description Meilisearch搜索功能Controller
 * @date 2025/4/18
 * @github https://github.com/macrozheng
 */
@RestController
@Tag(name = "MeilisearchController",description = "Meilisearch搜索功能")
@RequestMapping("/meilisearch")
public class MeilisearchController {

    @Operation(summary = "获取索引设置")
    @GetMapping("/getSettings")
    public CommonResult getSettings(){
        Settings settings = searchClient.index(MEILISEARCH_INDEX).getSettings();
        return CommonResult.success(settings);
    }

    @Operation(summary = "修改索引设置")
    @GetMapping("/updateSettings")
    public CommonResult updateSettings(){
        Settings settings = new Settings();
        settings.setFilterableAttributes(new String[]{"productCategoryName"});
        settings.setSortableAttributes(new String[]{"price"});
        TaskInfo info = searchClient.index(MEILISEARCH_INDEX).updateSettings(settings);
        return CommonResult.success(info);
    }
}
  • 之后就可以实现商品搜索的接口了,这里实现了包含关键字搜索、分页、按商品分类筛选、按价格排序的综合搜索功能。
/**
 * @auther macrozheng
 * @description Meilisearch搜索功能Controller
 * @date 2025/4/18
 * @github https://github.com/macrozheng
 */
@RestController
@Tag(name = "MeilisearchController",description = "Meilisearch搜索功能")
@RequestMapping("/meilisearch")
public class MeilisearchController {
    @Operation(summary = "根据关键字分页搜索商品")
    @GetMapping(value = "/search")
    @ResponseBody
    public CommonResult search(@RequestParam(required = false) String keyword,
                               @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                               @RequestParam(required = false, defaultValue = "5") Integer pageSize,
                               @RequestParam(required = false) String productCategoryName,
                               @RequestParam(required = false,value = "0->按价格升序;1->按价格降序") Integer order) {
        SearchRequest.SearchRequestBuilder searchBuilder = SearchRequest.builder();
        searchBuilder.page(pageNum);
        searchBuilder.hitsPerPage(pageSize);
        if(StrUtil.isNotEmpty(keyword)){
            searchBuilder.q(keyword);
        }
        if(StrUtil.isNotEmpty(productCategoryName)){
            searchBuilder.filter(new String[]{"productCategoryName="+productCategoryName});
        }
        if(order!=null){
            if(order==0){
                searchBuilder.sort(new String[]{"price:asc"});
            }else if(order==1){
                searchBuilder.sort(new String[]{"price:desc"});
            }
        }
        Searchable searchable = searchClient.index(MEILISEARCH_INDEX).search(searchBuilder.build());
        return CommonResult.success(searchable);
    }
}

功能演示

接下来我们来演示下上面实现的商品搜索功能。

  • 我们先调用/meilisearch/createIndex来实现创建索引并导入商品数据;

  • 导入成功后在Meilisearch的Mini Dashboard中就能看到对应的索引数据了,这里搜索下手机看下效果;

  • 之后我们再调用/meilisearch/updateSettings来修改索引设置;

  • 之后我们再调用/meilisearch/search接口来按关键字搜索商品、分页、筛选商品分类并按价格降序;

  • 最终返回结果如下。

两种搜索引擎对比

这里对Meilisearch和Elasticsearch两种搜索引擎做个对比。
MeilisearchElasticsearch
架构与设计轻量级、开箱即用分布式、部署配置复杂
性能50毫秒以内,中小数据集场景在大规模数据场景下性能更优
SDK支持多种语言、API简洁易用插件生态丰富、API学习成本高
中文支持‌‌原生支持需要额外配置中文分词插件
配置要求占用内存低占用内存高

总结

今天带大家使用Meilisearch实现了商品搜索,由于它原生支持中文,API也是简洁易用,使用起来确实挺方便的!

项目源码地址

https://github.com/macrozheng/spring-examples/tree/master/spring-meilisearch


macrozheng
1.1k 声望1.3k 粉丝