用
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
