ChromaDB09-数据库操作
1-docker进行ChromaDB部署仓库:https://gitee.com/enzoism/python_chromadb_write_data
2-chromaDB数据基础写入

向运行中的 ChromaDB 写入和查询数据
ChromaDB 支持两种运行模式:嵌入式(PersistentClient) 和 客户端/服务器模式(HttpClient) 。针对"运行中的"服务,通常指 Server 模式,下面分别说明。
一、连接运行中的 ChromaDB 服务
1. 以 Server 模式启动 Chroma
docker进行ChromaDB部署仓库:https://gitee.com/enzoism/python_chromadb_write_data
bash
# 方式一:CLI
chroma run --host 0.0.0.0 --port 8000 --path ./chroma_data
# 方式二:Docker
docker run -d -p 8000:8000 \
-v $(pwd)/chroma_data:/chroma/chroma \
-e IS_PERSISTENT=TRUE \
chromadb/chroma:latest
2. Python 客户端连接
bash
pip install chromadb
python
import chromadb
# 连接远程服务
client = chromadb.HttpClient(host="localhost", port=8000)
# 如果服务端配置了认证
# client = chromadb.HttpClient(
# host="localhost", port=8000,
# headers={"Authorization": "Bearer xxx"}
# )
# 检查心跳
print(client.heartbeat()) # 返回纳秒时间戳表示连接正常
若使用 嵌入式 模式(同一进程),则:
pythonclient = chromadb.PersistentClient(path="./chroma_data")
二、数据写入
1. 创建/获取集合
python
# 幂等:存在则获取,不存在则创建(新版 API 推荐)
collection = client.get_or_create_collection(
name="my_docs",
metadata={"hnsw:space": "cosine"} # 距离度量:cosine / l2 / ip
)
2. 插入数据(add)
python
collection.add(
ids=["id1", "id2", "id3"], # 必填,唯一
documents=["文档内容1", "文档内容2", "文档内容3"], # 文本(自动 embedding)
metadatas=[{"source": "a"}, {"source": "b"}, {"source": "c"}], # 可选
# embeddings=[[0.1, 0.2, ...], ...] # 可选,若提供则不自动 embedding
)
3. 更新/插入(upsert)
python
collection.upsert(
ids=["id1", "id4"],
documents=["更新后的内容1", "新内容4"],
metadatas=[{"source": "a2"}, {"source": "d"}],
)
4. 更新(update)与删除(delete)
python
collection.update(ids=["id1"], documents=["仅更新文档"])
collection.delete(ids=["id2"])
collection.delete(where={"source": "c"}) # 按元数据条件删除
注意 :
add要求 id 不存在,重复会报错;批量插入建议用upsert或分批(默认单批上限约 5461 条,可用client.get_max_batch_size()查询)。
三、数据查询
1. 语义检索(query)
python
results = collection.query(
query_texts=["我想了解机器学习"], # 或 query_embeddings=[[...]]
n_results=3,
where={"source": "a"}, # 元数据过滤(可选)
where_document={"$contains": "算法"}, # 文档内容过滤(可选)
include=["documents", "metadatas", "distances"]
)
print(results["ids"]) # [[...]]
print(results["documents"]) # [[...]]
print(results["distances"]) # 越小越相似(cosine 下 0~2)
2. 条件过滤查询(get)
python
# 按 id 查
collection.get(ids=["id1"])
# 按元数据查
collection.get(where={"source": "b"}, limit=10)
# 分页获取全部
collection.get(limit=100, offset=0)
3. 过滤运算符一览
| 场景 | 写法 |
|---|---|
| 等于 | {"source": "a"} |
| 不等于 | {"source": {"$ne": "a"}} |
| 范围 | {"year": {"$gte": 2020, "$lt": 2024}} |
| 包含任一 | {"tag": {"$in": ["x", "y"]}} |
| 逻辑与 | {"$and": [{"a": 1}, {"b": 2}]} |
| 逻辑或 | {"$or": [{"a": 1}, {"b": 2}]} |
| 文档包含 | where_document={"$contains": "关键词"} |
四、完整可运行示例
python
import chromadb
client = chromadb.HttpClient(host="localhost", port=8000)
col = client.get_or_create_collection("demo", metadata={"hnsw:space": "cosine"})
# 写入
col.upsert(
ids=["1", "2", "3"],
documents=[
"ChromaDB 是一个开源向量数据库",
"Python 是常用的编程语言",
"向量检索支持语义搜索",
],
metadatas=[{"lang": "zh", "cat": "db"},
{"lang": "zh", "cat": "lang"},
{"lang": "zh", "cat": "db"}],
)
# 查询
res = col.query(
query_texts=["向量数据库怎么用"],
n_results=2,
where={"cat": "db"},
include=["documents", "distances"],
)
for doc, dist in zip(res["documents"][0], res["distances"][0]):
print(f"{dist:.4f} {doc}")
五、常见注意事项
- Embedding 函数 :默认使用 Chroma 内置的
all-MiniLM-L6-v2(首次会下载模型)。生产环境建议显式传入自定义 embedding function,或自己算好向量用embeddings参数传入。 - 一致性:Server 模式写入默认是同步可见的,写入后立即可查。
- 并发:Server 端支持多客户端并发,但大批量写入建议分批(每批 1000~5000)。
- 持久化 :Docker 部署务必挂载
/chroma/chroma卷,否则容器重启数据丢失。 - 版本 :
chromadb>=0.4与旧版 API 有差异(如get_or_create_collection、query参数名),注意客户端与服务端版本匹配。
需要我补充 自定义 embedding 函数接入 、Node/JS 客户端写法 或 REST API 直接调用 的示例吗?