Chroma 安装使用与 RAG
一句话概述
Chroma 是最简单易用的开源向量数据库,三行 Python 代码就能创建集合、存储文档和执行语义搜索,自带嵌入模型无需额外配置,是学习 RAG(检索增强生成)的最佳入门工具。
核心知识点表格
| 知识点 | 说明 |
|---|
| 项目地址 | https://github.com/chroma-core/chroma |
| 官网 | https://www.trychroma.com |
| 最新版本 | v1.5.9(2026年5月) |
| GitHub Stars | 26,000+ |
| 核心功能 | 向量存储 + 语义搜索 |
| 运行模式 | 内存模式 / 本地持久化 / 客户端-服务器 |
| 开发语言 | Rust 内核 + Python/JS 接口 |
| 许可证 | Apache 2.0 |
| 每月下载量 | 1100 万+ |
安装与配置
Python 安装
# 安装 Chroma Python 客户端
pip install chromadb # 需要 Python >= 3.9
# 验证安装
python3 -c "import chromadb; print(chromadb.__version__)" # 打印版本号
JavaScript 安装
npm install chromadb # Node.js 环境
Docker 部署(客户端-服务器模式)
# 使用 Docker 运行 Chroma 服务器
docker run -d \
--name chroma \ # 容器名
-p 8000:8000 \ # 端口映射
-v chroma-data:/chroma/chroma \ # 数据持久化
ghcr.io/chroma-core/chroma:latest # 官方镜像
# 验证服务是否启动
curl http://localhost:8000/api/v2/heartbeat # 心跳检查
基本使用
内存模式(快速原型)
import chromadb # 导入 Chroma
# 创建内存客户端(数据在内存中,程序退出就丢失)
client = chromadb.Client()
# 创建一个集合(类似数据库中的表)
collection = client.create_collection(
name="bioinfo_docs" # 集合名称
)
# 添加文档(Chroma 自动生成嵌入向量)
collection.add(
documents=[
"宏基因组学是研究环境样本中所有微生物基因组的学科",
"16S rRNA 测序是鉴定细菌种类的常用方法",
"Alpha多样性指单个样本内的物种多样性",
"Beta多样性指不同样本间的物种组成差异",
"Shannon指数综合考虑物种丰富度和均匀度"
],
ids=["doc1", "doc2", "doc3", "doc4", "doc5"] # 每个文档的唯一 ID
)
# 语义搜索(找到最相关的文档)
results = collection.query(
query_texts=["什么是微生物多样性?"], # 搜索查询
n_results=3 # 返回最相关的 3 条
)
# 打印结果
for doc, distance in zip(results["documents"][0], results["distances"][0]):
print(f"相关度: {1-distance:.4f}") # 转换为相似度
print(f"内容: {doc}")
print("---")
持久化模式(数据存盘)
import chromadb
# 使用持久化客户端(数据保存到磁盘)
client = chromadb.PersistentClient(
path="./chroma_data" # 数据存储目录
)
# 获取或创建集合
collection = client.get_or_create_collection(
name="papers" # 集合名
)
# 添加文档(带元数据)
collection.add(
documents=[
"Kraken2 is a fast taxonomic classifier for metagenomics",
"MetaPhlAn uses marker genes for microbial profiling",
"MEGAHIT is a de novo assembler for metagenomics"
],
metadatas=[
{"tool": "kraken2", "type": "classifier"}, # 元数据
{"tool": "metaphlan", "type": "profiler"},
{"tool": "megahit", "type": "assembler"}
],
ids=["paper1", "paper2", "paper3"]
)
# 带元数据过滤的搜索
results = collection.query(
query_texts=["微生物物种分类工具"],
n_results=2,
where={"type": "classifier"} # 只搜索 classifier 类型
)
print(results["documents"]) # 搜索结果
print(results["metadatas"]) # 对应的元数据
客户端-服务器模式
import chromadb
# 连接到远程 Chroma 服务器
client = chromadb.HttpClient(
host="localhost", # 服务器地址
port=8000 # 服务器端口
)
# 后续操作与本地模式完全一样
collection = client.get_or_create_collection("my_data")
高级用法
构建简单 RAG 系统
import chromadb
import openai
# 第一步:初始化 Chroma 和 LLM 客户端
chroma_client = chromadb.PersistentClient(path="./rag_data")
llm_client = openai.Client(base_url="http://localhost:11434/v1", api_key="ollama")
# 第二步:创建知识库集合
knowledge_base = chroma_client.get_or_create_collection("knowledge")
# 第三步:导入知识文档
documents = [
"2型糖尿病患者的肠道菌群多样性显著降低",
"Akkermansia muciniphila 的丰度与糖尿病风险呈负相关",
"短链脂肪酸(SCFAs)在调节血糖中起重要作用",
"高膳食纤维饮食可以增加产丁酸菌的丰度",
"粪便微生物移植(FMT)是研究菌群功能的重要手段",
]
knowledge_base.add(
documents=documents,
ids=[f"doc_{i}" for i in range(len(documents))] # 生成 ID
)
# 第四步:RAG 检索 + 生成
def rag_answer(question):
"""检索相关知识,然后让 LLM 回答"""
# 检索相关文档
results = knowledge_base.query(
query_texts=[question],
n_results=3
)
# 拼接上下文
context = "\n".join(results["documents"][0])
# 调用 LLM 生成回答
response = llm_client.chat.completions.create(
model="llama3.1:8b",
messages=[
{"role": "system", "content": f"根据以下知识回答问题:\n{context}"},
{"role": "user", "content": question}
]
)
return response.choices[0].message.content
# 使用
answer = rag_answer("糖尿病和肠道菌群有什么关系?")
print(answer)
使用自定义嵌入模型
import chromadb
from chromadb.utils import embedding_functions
# 使用 HuggingFace 模型做嵌入
hf_ef = embedding_functions.HuggingFaceEmbeddingFunction(
model_name="BAAI/bge-small-zh-v1.5", # 中文嵌入模型
api_key="hf_xxx" # HuggingFace Token
)
# 使用 OpenAI 嵌入模型
openai_ef = embedding_functions.OpenAIEmbeddingFunction(
api_key="sk-xxx",
model_name="text-embedding-3-small"
)
# 使用 Ollama 本地嵌入
ollama_ef = embedding_functions.OllamaEmbeddingFunction(
url="http://localhost:11434/api/embeddings",
model_name="nomic-embed-text"
)
# 创建集合时指定嵌入函数
collection = client.create_collection(
name="chinese_docs",
embedding_function=hf_ef # 使用中文嵌入模型
)
混合搜索(BM25 + 向量)
# Chroma v1.5+ 支持稀疏向量搜索(BM25/SPLADE)
# 可以结合语义搜索和关键词搜索
collection = client.create_collection(
name="hybrid_search",
metadata={"hnsw:space": "cosine"} # 使用余弦距离
)
# 添加文档
collection.add(
documents=["..."],
ids=["..."]
)
# 使用 where_document 过滤包含特定关键词的文档
results = collection.query(
query_texts=["微生物组学分析"],
n_results=5,
where_document={"$contains": "微生物"} # 文档必须包含"微生物"
)
常见报错与解决
| 报错信息 | 原因 | 解决方法 |
|---|
Collection already exists | 集合已存在 | 使用 get_or_create_collection() 替代 create_collection() |
ID already exists | 文档 ID 重复 | 确保每个文档 ID 唯一,或使用 upsert() 替代 add() |
DimensionMismatch | 向量维度不匹配 | 同一集合必须使用同一个嵌入模型 |
sqlite3.OperationalError | SQLite 锁冲突 | 不要多个进程同时写入同一个持久化目录 |
No module named chromadb | 未安装 | pip install chromadb |
Connection refused (8000) | 服务器未启动 | 启动 Chroma 服务器或检查端口 |
速查表
# === Chroma Python SDK 速查 ===
import chromadb
# 客户端创建
client = chromadb.Client() # 内存模式
client = chromadb.PersistentClient(path="./data") # 持久化模式
client = chromadb.HttpClient(host="localhost") # 远程模式
# 集合操作
col = client.create_collection("name") # 创建
col = client.get_collection("name") # 获取
col = client.get_or_create_collection("name") # 获取或创建
client.delete_collection("name") # 删除
client.list_collections() # 列出所有
# 文档操作
col.add(documents=["..."], ids=["id1"]) # 添加
col.upsert(documents=["..."], ids=["id1"]) # 添加或更新
col.update(documents=["..."], ids=["id1"]) # 更新
col.delete(ids=["id1"]) # 删除
col.get(ids=["id1"]) # 获取
col.count() # 计数
# 搜索
col.query(query_texts=["查询"], n_results=5) # 语义搜索
col.query(query_texts=["查询"], where={"key": "val"}) # 元数据过滤
col.query(query_texts=["查询"], where_document={"$contains": "关键词"}) # 内容过滤
与同类工具对比
| 特性 | Chroma | Qdrant | Milvus | pgvector |
|---|
| 上手难度 | 极简(3行代码) | 简单 | 中等 | 中等 |
| 内嵌模式 | 支持(内存/文件) | 支持(内存) | 支持(Lite) | 需要 PostgreSQL |
| 自带嵌入 | 内置默认模型 | 需要外部 | 需要外部 | 需要外部 |
| 分布式 | 不支持 | 支持 | 支持 | 依赖 PostgreSQL |
| 适合场景 | 原型/小规模 | 中大规模 | 大规模 | 已有 PostgreSQL |
| 性能 | 中等 | 高 | 非常高 | 中等 |
| 云服务 | Chroma Cloud | Qdrant Cloud | Zilliz Cloud | 各云 PG 服务 |
选择建议:学习 RAG 和快速原型用 Chroma(最简单)。生产环境中小规模用 Qdrant。大规模分布式用 Milvus。已有 PostgreSQL 数据库就加 pgvector 扩展。