在我的mall電商實戰項目中,有使用過Elasticsearch實現商品搜索功能。其實商品搜索也可以使用Meilisearch來實現,實現起來還是非常方便的,今天就來帶大家實現一下!
前置知識
學習本文需要對Meilisearch有所瞭解,還沒有了解過它的小夥伴可以參考下這篇教程:
《超越Elasticsearch!號稱下一代搜索引擎,性能炸裂!》
下面是使用Meilisearch實現商品搜索的效果圖,搜索速度還是非常快的!
mall項目
由於我們會以mall項目中的商品搜索功能為例來講解Meilisearch的使用,這裏先簡單介紹下mall項目。
mall項目是一套基於 SpringBoot3 + Vue 的電商系統(Github標星60K),後端支持多模塊和2024最新微服務架構,採用Docker和K8S部署。包括前台商城項目和後台管理系統,能支持完整的訂單流程!涵蓋商品、訂單、購物車、權限、優惠券、會員、支付等功能!
- Boot項目:https://github.com/macrozheng/mall
- Cloud項目:https://github.com/macrozheng/mall-swarm
- 教程網站:https://www.macrozheng.com
項目演示:
實現商品搜索
接下來就來帶大家使用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服務都啓動起來,由於集成了SpringDoc,我們可以直接訪問它的API頁面來進行測試,訪問地址;http://localhost:8080/swagger-ui/index.html
- 我們先調用
/meilisearch/createIndex來實現創建索引並導入商品數據;
- 導入成功後在Meilisearch的Mini Dashboard中就能看到對應的索引數據了,這裏搜索下
手機看下效果;
- 之後我們再調用
/meilisearch/updateSettings來修改索引設置;
- 之後我們再調用
/meilisearch/search接口來按關鍵字搜索商品、分頁、篩選商品分類並按價格降序;
- 最終返回結果如下。
兩種搜索引擎對比
這裏對Meilisearch和Elasticsearch兩種搜索引擎做個對比。
| Meilisearch | Elasticsearch | |
|---|---|---|
| 架構與設計 | 輕量級、開箱即用 | 分佈式、部署配置複雜 |
| 性能 | 50毫秒以內,中小數據集場景 | 在大規模數據場景下性能更優 |
| SDK | 支持多種語言、API簡潔易用 | 插件生態豐富、API學習成本高 |
| 中文支持 | 原生支持 | 需要額外配置中文分詞插件 |
| 配置要求 | 佔用內存低 | 佔用內存高 |
總結
今天帶大家使用Meilisearch實現了商品搜索,由於它原生支持中文,API也是簡潔易用,使用起來確實挺方便的!
項目源碼地址
https://github.com/macrozheng/spring-examples/tree/master/spring-meilisearch