用
chromadb.Client()建好 collection、写入文档,一切正常;重启 Python 进程后get_collection报ValueError: Collection not found。根因是Client()是内存模式,数据只存在当前进程的 RAM 里,进程一结束就全没了。换PersistentClient(path="..."),数据落盘 SQLite,重启后原样取回。
Issue & Env(案发现场与环境)
- 业务场景:教程/示例代码里最常出现的写法——
chromadb.Client()建客户端,创建 collection、写入文档,当时查得到;换个终端或重启脚本再跑,collection 直接“消失”,get_collection报不存在。也有人形容为“数据丢了”。 - 环境:chromadb 任意版本,
chromadb.Client()或chromadb.EphemeralClient()。 - 关键区分:不是删了 collection,也不是磁盘损坏,是根本没往磁盘写过。
StackTrace(堆栈日志)
重启进程后访问 collection 的典型报错(fixdevs 原文):
ValueError: Collection not found
部分版本报 InvalidCollectionException,同一问题的不同异常类型:
chromadb.errors.InvalidCollectionException: Collection 'my_docs' does not exist.
Reproduce(复现代码)
import chromadb
# 第 1 个进程:内存模式建库写入
client = chromadb.Client() # 注意:没有 path 参数
col = client.get_or_create_collection("my_docs")
col.add(documents=["hello world"], ids=["1"])
print(col.count()) # 1,一切正常
# 重启 Python(新进程、新终端、或脚本跑完再跑一次)
client2 = chromadb.Client()
col2 = client2.get_collection("my_docs") # ValueError: Collection not found
两段代码之间没有任何删库操作,第 2 个进程就是找不到。
Root Cause(根因分析)
Client() 是内存模式,不落盘
Chroma 的客户端有三种形态,区别只在数据存哪:
| 客户端 | 数据存放 | 重启后 |
|---|---|---|
chromadb.Client() |
进程内存 | 数据全丢 |
chromadb.PersistentClient(path=...) |
磁盘(SQLite + HNSW 索引文件) | 数据仍在 |
chromadb.HttpClient(host, port) |
远端 server | 取决于 server |
新手从教程复制 Client() 最顺手,但教程通常没强调它不持久化。Client() 的所有 collection 和向量都驻留在当前进程的内存里,进程结束(脚本跑完、终端关掉、容器重启)即全部释放。
为什么还常看到报错而不是空结果
因为 collection 是“存在”的对象,get_collection 找不到会直接抛异常(Collection not found / InvalidCollectionException),而不是返回一个空 collection。所以表象是“报错”,不是“数据变空”,容易让人往路径、权限方向排查,绕远路。
容器场景的隐藏坑
用 PersistentClient(path="./chroma_data") 部署到容器,如果路径落在容器临时文件系统而不是挂载卷,容器重启照样清空。社区(theneuralbase 等)专门提醒:生产环境要把持久化路径挂到持久卷(PV/PVC),否则“持久化”名存实亡。
The Fix(解决方案)
第一步:换 PersistentClient
import chromadb
client = chromadb.PersistentClient(path="./chroma_db") # 加 path,落盘
col = client.get_or_create_collection("my_docs")
col.add(documents=["hello world"], ids=["1"])
第二步:重启后验证数据仍在
import chromadb
client = chromadb.PersistentClient(path="./chroma_db") # 同一个 path
col = client.get_collection("my_docs")
print(col.count()) # 1,数据还在
print(col.get()["documents"]) # ['hello world']
注意:path 必须是同一个目录。换个 path(哪怕是相对/绝对写法不一致)等于打开另一个空库,同样报 Collection not found。建议用绝对路径或环境变量统一管理:
import os
persist_dir = os.environ.get("CHROMA_PERSIST_DIR", "./chroma_db")
client = chromadb.PersistentClient(path=persist_dir)
第三步(容器场景):把 path 挂到持久卷
Docker / K8s 部署时,PersistentClient 的 path 要落在挂载卷(volume / PV)上,而不是容器临时文件系统,否则容器重建依旧丢数据。
References(参考来源)
- Fix: ChromaDB Not Working — Persistent Client, Collection Errors, and Embedding Function Issuesfixdevs-blog
- ChromaDB Collection Not Found: Fix InvalidCollectionException — Markaicodemarkaicode
- Resolve "ChromaDB collection does not exist" — InterviewsVectorinterviewsvector
- Persistent Client — Chroma 官方文档chroma-docs
