Chroma向量数据库快速入门
Chroma向量数据库快速入门
Chroma是RAG系统最易用的向量数据库,3行代码就能存取向量。
为什么选Chroma
| 特性 | Chroma | FAISS | Milvus | Qdrant |
|---|---|---|---|---|
| 易用性 | 极简 | 简单 | 复杂 | 中等 |
| 持久化 | 内置 | 需手动 | 内置 | 内置 |
| 元数据过滤 | 有 | 无 | 有 | 有 |
| 部署 | 无需 | 无需 | Docker | Docker |
| 适合 | 原型/中小 | 实验 | 大规模 | 生产 |
安装
pip install chromadb
基础用法
创建集合并存储
import chromadb
client = chromadb.PersistentClient(path="./chroma_db")
collection = client.create_collection("articles")
# 添加文档(Chroma自动生成Embedding)
collection.add(
documents=["Python是编程语言", "Java也是编程语言", "今天天气不错"],
metadatas=[{"source": "tech"}, {"source": "tech"}, {"source": "life"}],
ids=["1", "2", "3"]
)
查询
results = collection.query(
query_texts=["编程语言"],
n_results=2
)
print(results["documents"])
# [["Python是编程语言", "Java也是编程语言"]]
元数据过滤
results = collection.query(
query_texts=["编程"],
where={"source": "tech"}, # 只在tech分类中搜索
n_results=2
)
配合LangChain使用
from langchain_community.vectorstores import Chroma
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
# 加载文档
docs = [...] # 你的文档列表
# 切块
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
chunks = splitter.split_documents(docs)
# 用BGE做Embedding
embeddings = HuggingFaceEmbeddings(model_name="BAAI/bge-large-zh-v1.5")
# 存入Chroma
vectorstore = Chroma.from_documents(
documents=chunks,
embedding=embeddings,
persist_directory="./chroma_db",
collection_name="articles"
)
# 检索
results = vectorstore.similarity_search("什么是Python", k=3)
for doc in results:
print(doc.page_content[:100])
print(doc.metadata)
高级用法
更新文档
# 更新单个文档
collection.update(
ids=["1"],
documents=["Python是一种高级编程语言(更新版)"]
)
# 删除文档
collection.delete(ids=["3"])
自定义Embedding
# 用OpenAI Embedding
collection = client.create_collection(
"articles",
embedding_function=openai_embedding_function
)
批量操作
# 批量添加大量文档
batch_size = 1000
for i in range(0, len(documents), batch_size):
batch = documents[i:i+batch_size]
collection.add(
documents=batch,
ids=[str(j) for j in range(i, i+len(batch))]
)
性能优化
1. 选择合适的Embedding
- 中文:BGE-large-zh(1024维)
- 英文:all-MiniLM-L6-v2(384维,更快)
2. 调整chunk_size
- 太小:语义不完整
- 太大:检索不精准
- 推荐:300-500字,重叠50字
3. 使用重排序
# 先检索top-20,再用reranker重排
results = collection.query(query_texts=["..."], n_results=20)
# 用BGE-reranker重排
部署
本地文件
client = chromadb.PersistentClient(path="./chroma_db")
服务器模式
chroma run --host 0.0.0.0 --port 8000
client = chromadb.HttpClient(host="localhost", port=8000)
Chroma是RAG系统原型开发的最快路径。数据量到百万级再考虑换Milvus或Qdrant。