实战案例:课程搜索引擎
本章定位:综合运用全教程所学知识,从零搭建一个完整的课程搜索引擎。覆盖 Mapping 设计、搜索查询、聚合分析、自定义排序和性能优化。
业务需求
飞翔科技的在线教育平台需要升级课程搜索功能:
- 搜索:按课程名称、描述、大纲搜索(支持中文分词)
- 筛选:按分类、教师、价格范围筛选
- 排序:相关性 + 报名人数 + 评分综合排序
- 聚合:按分类统计课程数、平均价格、平均评分
- 高亮:搜索结果中高亮匹配词
完整示例
第一步:Mapping 设计
PUT /courses
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1,
"analysis": { "analyzer": { "ik_smart_analyzer": { "type": "custom", "tokenizer": "ik_smart", "filter": ["lowercase"] } } }
},
"mappings": {
"dynamic": "strict",
"properties": {
"title": { "type": "text", "analyzer": "ik_max_word", "search_analyzer": "ik_smart", "fields": { "keyword": { "type": "keyword" } } },
"teacher": { "type": "keyword" },
"category": { "type": "keyword" },
"description": { "type": "text", "analyzer": "ik_max_word" },
"outline": { "type": "text", "analyzer": "ik_max_word", "norms": false },
"price": { "type": "scaled_float", "scaling_factor": 100 },
"rating": { "type": "float" },
"enrollment_count": { "type": "integer" },
"publish_date": { "type": "date", "format": "yyyy-MM-dd" },
"tags": { "type": "keyword" }
}
}
}
第二步:综合搜索
POST /courses/_search
{
"query": {
"function_score": {
"query": {
"bool": {
"must": [{ "multi_match": { "query": "数据", "fields": ["title^3", "description", "outline"] } }],
"filter": [
{ "terms": { "category.keyword": ["数据科学", "数据工程"] } },
{ "range": { "price": { "gte": 10000, "lte": 50000 } } },
{ "term": { "difficulty": "中级" } }
]
}
},
"functions": [
{ "field_value_factor": { "field": "enrollment_count", "factor": 0.1, "modifier": "log1p", "missing": 0 }, "weight": 1.5 },
{ "field_value_factor": { "field": "rating", "factor": 1, "modifier": "none", "missing": 1 }, "weight": 2 }
],
"score_mode": "sum",
"boost_mode": "multiply"
}
}
}
第三步:聚合分析
POST /courses/_search
{
"size": 0,
"aggs": {
"by_category": {
"terms": { "field": "category.keyword", "size": 10 },
"aggs": {
"avg_price": { "avg": { "field": "price" } },
"avg_rating": { "avg": { "field": "rating" } },
"total_enrollment": { "sum": { "field": "enrollment_count" } }
}
}
}
}
小结
本实战案例覆盖了 Elasticsearch 完整技术栈:Mapping 设计(中文分词 + keyword 子字段 + norms 优化)→ 数据写入(Bulk API)→ 搜索查询(multi_match + bool + function_score)→ 聚合分析(嵌套 terms + avg)→ 运维部署(ILM + 监控)。核心心得:Mapping 设计决定搜索质量上限,function_score 让业务规则融入排序,ILM 让运维自动化。