在构建AI应用——特别是RAG系统、推荐引擎、语义搜索时,你很快会遇到"向量数据库"这个概念。它是什么?为什么传统数据库不够用?如何选择合适的向量数据库?本文将为AI开发者提供全面的入门指南。
什么是向量数据库
从传统数据库到向量数据库
传统数据库(如MySQL、PostgreSQL)擅长:
- 精确匹配查询:"找出价格=99元的商品"
- 范围查询:"找出价格在50-100元的商品"
- 关系查询:"找出购买过商品A的用户"
局限性:无法理解"语义相似性"。
例如,搜索"便宜的笔记本电脑":
- 传统数据库:需要商品描述中精确包含这些词
- 无法匹配"性价比高的笔记本"、"学生用laptop"等语义相似的商品
向量数据库擅长:
- 语义相似性搜索
- 多模态检索(文本、图片、音频)
- 推荐系统
- 异常检测
核心概念:向量与嵌入
向量(Vector):一个数字数组,例如[0.2, -0.5, 0.8, ...]
嵌入(Embedding):将文本、图片等数据转换为向量的过程。
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('all-MiniLM-L6-v2')
# 文本转向量
text = "AI正在改变世界"
vector = model.encode(text)
print(vector.shape) # (384,) - 384维向量
print(vector[:5]) # [0.0234, -0.1567, 0.3421, -0.0891, 0.2134]
关键特性:语义相似的文本,其向量在高维空间中距离较近。
text1 = "AI正在改变世界"
text2 = "人工智能正在改变世界"
text3 = "今天天气很好"
vec1 = model.encode(text1)
vec2 = model.encode(text2)
vec3 = model.encode(text3)
from sklearn.metrics.pairwise import cosine_similarity
print(cosine_similarity([vec1], [vec2])) # 0.95(非常相似)
print(cosine_similarity([vec1], [vec3])) # 0.12(不相似)
相似度搜索
向量数据库的核心功能:给定查询向量,找出最相似的K个向量。
常用距离度量:
- 余弦相似度:衡量方向相似性(-1到1,1最相似)
- 欧氏距离:衡量空间距离
- 点积:综合方向和长度
主流向量数据库对比
Pinecone
特点:
- 完全托管的云服务
- 易用性极高
- 自动扩展
- 支持实时更新
定价:
- 免费层:1个索引,100万向量
- 付费:$70/月起
适用场景:快速原型、中小规模应用
import pinecone
pinecone.init(api_key="YOUR_API_KEY", environment="us-west1-gcp")
# 创建索引
pinecone.create_index("my-index", dimension=384, metric="cosine")
# 插入向量
index = pinecone.Index("my-index")
index.upsert(vectors=[
("id1", [0.1, 0.2, ...]), # 384维
("id2", [0.3, 0.4, ...])
])
# 搜索
results = index.query(vector=[0.15, 0.25, ...], top_k=5)
Weaviate
特点:
- 开源
- 支持多模态(文本、图片)
- 内置向量化(可调用OpenAI、Cohere等)
- GraphQL API
部署:
- 云托管:Weaviate Cloud Services
- 自托管:Docker、Kubernetes
适用场景:需要多模态检索、希望本地部署
import weaviate
client = weaviate.Client("http://localhost:8080")
# 创建schema
schema = {
"classes": [{
"class": "Article",
"properties": [
{"name": "title", "dataType": ["string"]},
{"name": "content", "dataType": ["text"]}
]
}]
}
client.schema.create(schema)
# 插入数据(自动向量化)
client.data_object.create(
data_object={"title": "AI应用", "content": "..."},
class_name="Article"
)
# 搜索
result = client.query.get("Article", ["title", "content"]).with_near_text({
"concepts": ["人工智能"]
}).with_limit(5).do()
Milvus
特点:
- 开源
- 高性能(十亿级向量)
- 支持GPU加速
- 丰富的索引类型(IVF、HNSW)
部署:
- Milvus Standalone(单机)
- Milvus Cluster(分布式)
- Zilliz Cloud(托管版)
适用场景:大规模、高性能需求
from pymilvus import connections, Collection, FieldSchema, CollectionSchema, DataType
connections.connect("default", host="localhost", port="19530")
# 定义schema
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
FieldSchema(name="vector", dtype=DataType.FLOAT_VECTOR, dim=384)
]
schema = CollectionSchema(fields)
# 创建集合
collection = Collection("articles", schema)
# 插入向量
collection.insert([[1, 2], [[0.1, 0.2, ...], [0.3, 0.4, ...]]])
# 创建索引
collection.create_index("vector", {"index_type": "IVF_FLAT", "metric_type": "L2"})
# 搜索
collection.load()
results = collection.search(
data=[[0.15, 0.25, ...]],
anns_field="vector",
param={"metric_type": "L2"},
limit=5
)
Chroma
特点:
- 开源
- 嵌入式(类似SQLite)
- 易集成LangChain、LlamaIndex
- 轻量级
适用场景:原型开发、小规模应用
import chromadb
client = chromadb.Client()
# 创建集合
collection = client.create_collection("my_collection")
# 添加文档(自动向量化)
collection.add(
documents=["这是第一篇文章", "这是第二篇文章"],
ids=["id1", "id2"]
)
# 搜索
results = collection.query(
query_texts=["文章内容"],
n_results=5
)
对比总结
| 特性 | Pinecone | Weaviate | Milvus | Chroma |
|---|---|---|---|---|
| 开源 | ❌ | ✅ | ✅ | ✅ |
| 易用性 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| 性能 | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
| 扩展性 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐ |
| 成本 | 高 | 中 | 低(自托管) | 免费 |
| 多模态 | ❌ | ✅ | ✅ | ❌ |
RAG系统中的向量数据库
在RAG系统中,向量数据库扮演"知识库"角色。
典型流程
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import Pinecone
from langchain.text_splitter import RecursiveCharacterTextSplitter
# 1. 加载文档
documents = load_documents("knowledge_base/")
# 2. 分块
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
chunks = text_splitter.split_documents(documents)
# 3. 向量化并存入向量数据库
embeddings = OpenAIEmbeddings()
vectorstore = Pinecone.from_documents(chunks, embeddings, index_name="rag-index")
# 4. 检索
query = "什么是RAG?"
relevant_docs = vectorstore.similarity_search(query, k=3)
# 5. 生成答案
context = "\n".join([doc.page_content for doc in relevant_docs])
answer = llm.generate(f"基于以下内容回答:\n{context}\n\n问题:{query}")
性能优化
分块策略:
- 太小:缺乏上下文
- 太大:检索不精准
- 推荐:500-1000字符,重叠50-100字符
元数据过滤:
# 不仅语义搜索,还加上元数据过滤
results = vectorstore.similarity_search(
query="AI应用",
k=5,
filter={"category": "技术", "date": {"$gte": "2025-01-01"}}
)
混合搜索:结合关键词搜索和向量搜索,参考混合搜索策略。
选型建议
原型阶段
使用Chroma或Pinecone免费层:
- 快速上手
- 无需运维
- 成本低
中小规模生产
使用Pinecone或Weaviate Cloud:
- 托管服务,省心
- 自动扩展
- 性能足够
大规模生产
使用Milvus Cluster或Weaviate自托管:
- 成本更低(自托管)
- 性能更强
- 完全控制
特殊需求
- 多模态:Weaviate或Milvus
- 极致性能:Milvus + GPU
- 预算极度有限:PostgreSQL + pgvector(开源插件)
最佳实践
1. 选择合适的嵌入模型
- 英文:
all-MiniLM-L6-v2(快速,384维) - 中文:
paraphrase-multilingual-MiniLM-L12-v2 - 高质量:
text-embedding-ada-002(OpenAI,1536维)
权衡:维度越高越准确,但存储和计算成本越高。
2. 定期重建索引
随着数据增长,索引可能降级,定期重建可提升性能。
3. 监控性能指标
- 检索延迟:P50、P95、P99
- 准确率:检索到的文档是否真正相关
- 召回率:相关文档是否被检索到
4. 备份
向量数据库也是数据库,需要定期备份。
未来趋势
多模态统一索引:文本、图片、音频在同一向量空间。
自适应索引:根据查询模式自动调整索引结构。
边缘向量数据库:在移动设备上运行的轻量级向量数据库。
与传统数据库融合:PostgreSQL、MongoDB等传统数据库原生支持向量搜索。
向量数据库是AI应用的基础设施,掌握它是构建现代AI系统的必备技能。从小规模原型到大规模生产,选择合适的向量数据库,优化性能,是AI工程师的核心能力之一。
相关资源
RAG技术:
向量检索:
应用实践:
- AI Agent开发 – Agent集成
- 市场情报平台 – 实战案例
- API文档 – 技术文档
SearchCans提供高性价比的Bing搜索API和Reader API服务,专为AI Agent和开发者打造。立即体验 →