一、接口设计规范
- RESTful API设计
# 请求示例
GET /api/v1/search?keyword=连衣裙&page=1&sort=price_asc
Headers: {
"X-APP-ID": "mogu_jie",
"Authorization": "Bearer token"
}
- 核心参数说明
- keyword:必填,支持UTF-8编码
- page:分页参数(默认1)
- sort:排序方式(sales_desc/price_asc/price_desc)
二、Java SpringBoot实现
@RestController
@RequestMapping("/api/v1")
public class SearchController {
@Autowired
private ElasticsearchService esService;
@GetMapping("/search")
public ResponseEntity<SearchResult> searchProducts(
@RequestParam String keyword,
@RequestParam(defaultValue = "1") int page,
@RequestParam(required = false) String sort) {
// 构建ES查询条件
SearchQuery query = new SearchQueryBuilder()
.withKeyword(keyword)
.withPage(page)
.withSort(sort)
.build();
return ResponseEntity.ok(esService.search(query));
}
}
三、Elasticsearch查询优化
- 索引设计
PUT /products
{
"mappings": {
"properties": {
"title": {"type": "text", "analyzer": "ik_max_word"},
"tags": {"type": "keyword"},
"price": {"type": "double"}
}
}
}
2. 查询DSL示例
{
"query": {
"bool": {
"must": [
{"match": {"title": "连衣裙"}},
{"range": {"price": {"gte": 50}}}
]
}
},
"from": 0,
"size": 20,
"sort": [{"sales": "desc"}]
}
四、性能优化方案
- 多级缓存策略
- Redis缓存热门搜索词(TTL 30分钟)
- 本地缓存商品基本信息(Caffeine实现)
- 降级方案
- 超时自动切换MySQL简易搜索
- 返回兜底的热门商品数据