ChromaDB09-数据库操作

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())  # 返回纳秒时间戳表示连接正常

若使用 嵌入式 模式(同一进程),则:

python 复制代码
client = 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}")

五、常见注意事项

  1. Embedding 函数 :默认使用 Chroma 内置的 all-MiniLM-L6-v2(首次会下载模型)。生产环境建议显式传入自定义 embedding function,或自己算好向量用 embeddings 参数传入。
  2. 一致性:Server 模式写入默认是同步可见的,写入后立即可查。
  3. 并发:Server 端支持多客户端并发,但大批量写入建议分批(每批 1000~5000)。
  4. 持久化 :Docker 部署务必挂载 /chroma/chroma 卷,否则容器重启数据丢失。
  5. 版本 :chromadb>=0.4 与旧版 API 有差异(如 get_or_create_collection、query 参数名),注意客户端与服务端版本匹配。

需要我补充 自定义 embedding 函数接入 、Node/JS 客户端写法 或 REST API 直接调用 的示例吗?

相关推荐
科力锐品牌君18 分钟前
信创进入核心系统深水区:X86 与国产架构长期并存,如何落地统一灾备?
运维·网络·数据库·数据安全·灾备
在角落发呆35 分钟前
sqlserver 如何备份数据库:从手动备份到自动定时、异地容灾的完整方案
数据库·windows·备份·数据备份
xixiaoyunya44 分钟前
MySQL 全库备份:用 mysqldump 打好基线,再补上自动化与异地能力
数据库·mysql·自动化
你看我名字1 小时前
OpenAI 兼容接口能不能直接接入:数眼智能大模型 API 迁移实战与兼容性检查
android·java·数据库·大模型平台选择
箓维2 小时前
MySQL_数据库基础与库表操作
数据库·mysql·oracle
CoderYanger3 小时前
Java EE 进阶:15. Linux基本使用和程序部署(第二弹):部署 Web 项目到 Linux
linux·服务器·数据库·spring boot·spring·阿里云·java-ee
跟我学机器学习3 小时前
让 PostgreSQL 具备向量检索能力:pgvector 的安装、启用与验证
数据库·postgresql
两点王爷3 小时前
Redis 高频面试题:除了缓存,Redis 还有哪些用途?
数据库·redis·缓存
飞花漫卷,情随岁迁3 小时前
Linux 排障与性能监控
linux·运维·服务器·网络·数据库·mysql·oracle
富贵儿9983 小时前
NL2SQL 实践手记 10:从命令行到网页查询——把整个系列串起来
数据库·python·sql·ai·自然语言处理·langchain