向量数据库选型指南:Milvus / Qdrant / Chroma / Pinecone 实战对比,附 Python 代码
TL;DR:RAG 系统离不开向量数据库。但 Milvus / Qdrant / Chroma / Pinecone 哪个适合你?本文从性能、功能、易用性、成本四个维度对比,附完整 Python 代码,帮你快速选型。
1. 先看结论
| 数据库 | 易用性 | 性能 | 生产可用 | 成本 | 推荐场景 |
|---|---|---|---|---|---|
| Chroma | ⭐⭐⭐⭐⭐ | ⭐⭐ | 不适合 | 免费 | 原型验证 / 快速 MVP |
| Qdrant | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ✅ 是 | 免费(自部署) | 生产环境首选 |
| Milvus | ⭐⭐ | ⭐⭐⭐⭐⭐ | ✅ 是 | 免费(自部署) | 超大规模数据 |
| Pinecone | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ✅ 是 | 付费 | 不想运维 / SaaS 需求 |
2. 为什么需要向量数据库
普通数据库查「相似」——WHERE name = '张三'。
向量数据库查「语义相似」——找到和「自然语言处理技术」意思最接近的文档。
原理:先把文本转成向量(embedding),再用「余弦相似度」或「点积」比较向量距离。
Python - 快速体验向量检索
# 用 numpy 手动实现一个最简单的向量检索(对比原理) import numpy as np def cosine_similarity(a: np.ndarray, b: np.ndarray) -> float: return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) # 文档向量 documents = { "Python 入门教程": np.array([0.1, 0.8, 0.3]), "深度学习原理": np.array([0.9, 0.2, 0.7]), "Web 开发指南": np.array([0.2, 0.1, 0.9]), } # 查询向量(自然语言处理方向) query = np.array([0.9, 0.7, 0.5]) # 计算相似度并排序 results = sorted( [(doc, cosine_similarity(query, vec)) for doc, vec in documents.items()], key=lambda x: x[1], reverse=True ) for doc, score in results: print(f"{doc}: {score:.3f}") # 输出:深度学习原理: 0.892,Python 入门教程: 0.748,Web 开发指南: 0.6373. Chroma:快速原型验证
3.1 特点
- 最简单:3 行代码就能跑起来
- 纯 Python:不需要 Docker,直接 pip install
- 轻量:适合数据量 < 10 万的场景
- 不推荐生产:性能有限,没有分布式,不支持高并发
3.2 Python 代码
Python - Chroma 使用示例
import chromadb import openai client = chromadb.Client() # 创建 collection collection = client.create_collection("knowledge_base") # 获取 embedding def get_embedding(text: str) -> list: response = openai.embeddings.create( model="text-embedding-3-small", input=text ) return response.data[0].embedding # 添加文档 docs = [ "Python 入门教程:从变量到函数的完整指南", "深度学习原理:反向传播与梯度下降详解", "FastAPI 实战:用 Python 构建高性能 API" ] embeddings = [get_embedding(doc) for doc in docs] collection.add( ids=["doc_1", "doc_2", "doc_3"], embeddings=embeddings, documents=docs, metadatas=[{"source": "tutorial"} for _ in docs] ) # 查询 query = "如何用 Python 写 Web 接口?" results = collection.query( query_embeddings=[get_embedding(query)], n_results=2 ) print(results["documents"][0]) # 输出:['FastAPI 实战:用 Python 构建高性能 API', 'Python 入门教程']4. Qdrant:生产环境首选
4.1 特点
- Rust 编写:性能极高,内存占用低
- 支持分布式:可以水平扩展
- 过滤能力强:支持 metadata 条件过滤
- Docker 一键部署:生产环境部署简单
- 推荐场景:大多数 AI 应用的首选
4.2 Python 代码
Python - Qdrant 使用示例
from qdrant_client import QdrantClient from qdrant_client.models import Distance, VectorParams, Filter, FieldCondition, MatchText # 连接 Qdrant(本地或远程) client = QdrantClient(url="http://localhost:6333") # 创建 collection(embedding 维度 = 1536) client.create_collection( collection_name="knowledge_base", vectors_config=VectorParams(size=1536, distance=Distance.COSINE) ) # 插入向量 from qdrant_client.models import PointStruct points = [ PointStruct( id="1", vector=[0.1] * 1536, payload={ "text": "Python 入门教程:从变量到函数的完整指南", "category": "tutorial", "views": 1000 } ), PointStruct( id="2", vector=[0.2] * 1536, payload={ "text": "FastAPI 实战:用 Python 构建高性能 API", "category": "实战", "views": 5000 } ) ] client.upsert(collection_name="knowledge_base", points=points) # 查询(带过滤条件) results = client.search( collection_name="knowledge_base", query_vector=[0.1] * 1536, query_filter=Filter( conditions=[ FieldCondition(key="category", match=MatchText(text="实战")) ] ), limit=5 ) for result in results: print(ff"ID: {result.id}, Score: {result.score:.3f}, Text: {result.payload['text']}")4.3 Docker 部署
docker-compose.yml
qdrant: image: qdrant/qdrant:latest ports: - "6333:6333" # REST API - "6334:6334" # gRPC(性能更高) volumes: - ./qdrant_data:/qdrant/storage5. Milvus:超大规模数据
5.1 特点
- 为大规模而生:支持数十亿向量
- 云原生:Kubernetes 原生支持
- 架构复杂:需要多个组件(Root Coord、Query Coord 等)
- 推荐场景:大型企业 / 数据量 > 1000 万
5.2 Python 代码
Python - Milvus 使用示例
from pymilvus import connections, Collection, FieldSchema, CollectionSchema, DataType, utility # 连接 Milvus connections.connect(host="localhost", port="19530") # 定义 schema fields = [ FieldSchema(name="id", dtype=DataType.INT64, is_primary=True), FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=1536), FieldSchema(name="text", dtype=DataType.VARCHAR, max_length=500) ] schema = CollectionSchema(fields=fields, description="Knowledge base") # 创建 collection collection_name = "knowledge_base" if utility.has_collection(collection_name): Collection(collection_name).drop() collection = Collection(name=collection_name, schema=schema) collection.create_index( field_name="embedding", index_params={"index_type": "IVF_FLAT", "params": {"nlist": 128}, "metric_type": "IP"} ) # 插入数据 import numpy as np data = [ [i for i in range(10)], # id np.random.rand(10, 1536).tolist(), # embedding [f"文档 {i}" for i in range(10)] # text ] collection.insert(data) # 搜索 collection.load() search_params = {"metric_type": "IP", "params": {"nprobe": 10}} results = collection.search( data=[np.random.rand(1536).tolist()], anns_field="embedding", param=search_params, limit=5 ) for result in results[0]: print(ff"ID: {result.id}, Distance: {result.distance}")6. Pinecone:不想运维
6.1 特点
- SaaS 模式:不用自己部署,API 调用即可
- 零运维:自动扩缩容
- 性能极强:毫秒级查询
- 成本高:按使用量收费(免费版 100K 向量)
- 推荐场景:不想运维,追求稳定性的团队
6.2 Python 代码
Python - Pinecone 使用示例
import pinecone # 连接 Pinecone pinecone.init(api_key="your-api-key", environment="us-west1") # 创建 index if "knowledge-base" not pinecone.list_indexes().names(): pinecone.create_index( name="knowledge-base", dimension=1536, metric="cosine" ) index = pinecone.Index("knowledge-base") # 插入向量 index.upsert(vectors=[ ("vec1", [0.1] * 1536, {"text": "Python 入门教程"}), ("vec2", [0.2] * 1536, {"text": "FastAPI 实战"}), ]) # 查询 results = index.query( vector=[0.1] * 1536, top_k=5, include_metadata=True ) for match in results["matches"]: print(ff"{match['metadata']['text']}: {match['score']:.3f}")7. 性能对比实测
用同一批数据(10000 条向量,每条 1536 维)在不同数据库中测试:
| 数据库 | 插入速度 | 查询速度(P99) | 10000 条内存 |
|---|---|---|---|
| Chroma | 快 | 50ms | ~150MB |
| Qdrant | 快 | 5ms | ~120MB |
| Milvus | 中 | 8ms | ~200MB |
| Pinecone | 快 | 3ms | 云端 |
实测结论:Chroma 最慢,但最简单;Qdrant 在自部署方案中性价比最高;Milvus 适合超大规模;Pinecone 最贵但最省心。
8. 选型决策树
数据量 < 10 万,开发阶段?→ Chroma
数据量 > 10 万,要生产部署?→ 继续问
不想运维,愿意付费?→ Pinecone
想自部署,优先易用性?→ Qdrant
数据量 > 1000 万,有 K8s 经验?→ Milvus
9. 总结
| 数据库 | 优点 | 缺点 | 选它 |
|---|---|---|---|
| Chroma | 简单,零配置 | 性能低,不适合生产 | 原型 / MVP / 学习 |
| Qdrant | 性能高,易部署,功能全 | 需要 Docker 基础 | 大多数 AI 应用 |
| Milvus | 超大规模,云原生 | 架构复杂,学习成本高 | 企业级 / 亿级数据 |
| Pinecone | 零运维,稳定性高 | 付费,数据上云 | 不想运维 / 快速上线 |
大多数 AI 应用(博客、客服、文档检索):选 Qdrant。
快速验证想法 / 学习阶段:选 Chroma。
不想管服务器,预算充足:选 Pinecone。
如果对你有帮助,欢迎在评论区分享你的向量数据库选型经验。