语义搜索和推荐系统是向量数据库最传统的应用场景。本节用两个实战案例分别讲解。

企业内部有上万篇技术文档、设计文档、周报等。员工通过自然语言搜索想要的内容,而不是精确的关键词匹配。
from pymilvus import Collection, FieldSchema, CollectionSchema, DataType schema = CollectionSchema(fields=[ FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=True), FieldSchema(name="title", dtype=DataType.VARCHAR, max_length=256), FieldSchema(name="content", dtype=DataType.VARCHAR, max_length=65535), FieldSchema(name="doc_type", dtype=DataType.VARCHAR, max_length=32), FieldSchema(name="department", dtype=DataType.VARCHAR, max_length=64), FieldSchema(name="author", dtype=DataType.VARCHAR, max_length=64), FieldSchema(name="created_at", dtype=DataType.INT64), FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=768), ]) collection = Collection(name="enterprise_docs", schema=schema) collection.create_index( "embedding", {"index_type": "HNSW", "params": {"M": 32, "efConstruction": 256}, "metric_type": "COSINE"}, )
def semantic_search(query: str, doc_type: str = None, department: str = None, top_k: int = 10): """语义搜索接口""" query_vec = embed_texts([query])[0] # 构建过滤条件 conditions = [] if doc_type: conditions.append(f'doc_type == "{doc_type}"') if department: conditions.append(f'department == "{department}"') expr = " and ".join(conditions) if conditions else None results = collection.search( data=[query_vec], anns_field="embedding", param={"metric_type": "COSINE", "params": {"ef": 100}}, limit=top_k, expr=expr, output_fields=["title", "content", "doc_type", "department", "created_at"], ) return [ { "title": hit.entity.get("title"), "score": hit.score, "type": hit.entity.get("doc_type"), "department": hit.entity.get("department"), "snippet": hit.entity.get("content", "")[:200], } for hit in results[0] ]
衡量语义搜索质量的关键指标:
def evaluate_search(test_queries, ground_truths, top_k=10): """评估搜索质量""" ndcg_scores = [] mrr_scores = [] for query, gt in zip(test_queries, ground_truths): results = semantic_search(query, top_k=top_k) retrieved_ids = [r["title"] for r in results] # 计算指标 relevance = [1 if r in gt else 0 for r in retrieved_ids] # DCG dcg = sum(rel / np.log2(i + 2) for i, rel in enumerate(relevance)) # IDCG ideal = sorted(relevance, reverse=True) idcg = sum(rel / np.log2(i + 2) for i, rel in enumerate(ideal)) ndcg = dcg / idcg if idcg > 0 else 0 ndcg_scores.append(ndcg) # MRR for i, rel in enumerate(relevance): if rel == 1: mrr_scores.append(1.0 / (i + 1)) break else: mrr_scores.append(0) print(f"NDCG@{top_k}: {np.mean(ndcg_scores):.4f}") print(f"MRR: {np.mean(mrr_scores):.4f}")
基于用户的浏览/购买行为,推荐相似商品。
# Collection 中存储商品向量 schema = CollectionSchema(fields=[ FieldSchema(name="product_id", dtype=DataType.VARCHAR, max_length=32, is_primary=True), FieldSchema(name="name", dtype=DataType.VARCHAR, max_length=256), FieldSchema(name="category", dtype=DataType.VARCHAR, max_length=64), FieldSchema(name="brand", dtype=DataType.VARCHAR, max_length=64), FieldSchema(name="price", dtype=DataType.FLOAT), FieldSchema(name="image_embedding", dtype=DataType.FLOAT_VECTOR, dim=512), # CLIP 图片向量 FieldSchema(name="text_embedding", dtype=DataType.FLOAT_VECTOR, dim=768), # 文本向量 ]) collection = Collection(name="products", schema=schema)
from pymilvus import AnnSearchRequest, WeightedRanker def recommend_similar_products(product_id: str, top_k: int = 10): """推荐和指定商品相似的其他商品""" # 获取目标商品的向量 product = collection.query( expr=f'product_id == "{product_id}"', output_fields=["image_embedding", "text_embedding"], ) if not product: return [] img_vec = product[0]["image_embedding"] text_vec = product[0]["text_embedding"] # 多向量搜索 reqs = [ AnnSearchRequest( data=[img_vec], anns_field="image_embedding", param={"metric_type": "COSINE", "params": {"ef": 100}}, limit=50, ), AnnSearchRequest( data=[text_vec], anns_field="text_embedding", param={"metric_type": "COSINE", "params": {"ef": 100}}, limit=50, ), ] results = collection.hybrid_search( reqs=reqs, ranker=WeightedRanker(0.6, 0.4), # 图片权重 0.6,文本权重 0.4 limit=top_k, output_fields=["product_id", "name", "category", "brand", "price"], expr=f'product_id != "{product_id}"', # 排除自己 ) return [ { "product_id": hit.id, "name": hit.entity.get("name"), "category": hit.entity.get("category"), "brand": hit.entity.get("brand"), "price": hit.entity.get("price"), } for hit in results[0] ]
def recommend_for_user(user_behavior_embeddings, top_k: int = 20): """基于用户行为序列的推荐""" # user_behavior_embeddings 是用户近期浏览商品的向量平均值 results = collection.search( data=[user_behavior_embeddings], anns_field="text_embedding", param={"metric_type": "COSINE", "params": {"ef": 100}}, limit=top_k, output_fields=["product_id", "name", "price"], expr="price > 0 and category != '配件'", # 过滤不想要的类别 ) return results
推荐系统需要频繁更新商品数据和用户画像。利用 Milvus 的流式写入能力:
# 新商品上架,实时写入 collection.insert([product_id, name, category, brand, price, img_vec, text_vec]) # 几秒后即可被搜索到
语义搜索上线后需要持续维护:
推荐系统还要定期核对推荐列表的多样性,避免长期推荐同一类商品造成体验疲劳,可以结合 Grouping Search 按品牌或类目做去重。
语义搜索的关键是选择合适的 Embedding 模型和搜索参数,并通过 NDCG/MRR 等指标评估效果。推荐系统通常需要多向量字段(图片+文本)和混合搜索,Grouping Search 可以避免结果被同一品牌刷屏。实时更新能力是 Milvus 的优势,适合推荐场景的频繁数据变化。