1. 环境
环境:
miniconda==24.11.1
python==3.12.1
2. 介绍
chromadb 是一个开源的向量数据库,专门用于存储和检索高维向量数据,轻量级,适合快速原型开发,适合新手练习。
3. 安装
pip install chromadb
3.1 持久客户端运行
chroma run --path /path
/path 是文件存储磁盘的路径
这样就说明已经启动,默认是8000端口
http://localhost:8000/docs
启动后可以打开swagger文档,有接口可以操作数据库
官方文档
启动后Getting started guide后是官方文档可以自行查看
3.X 安装过程的问题
这是因为chroma-hnswlib,它依赖于 hnswlib,而 hnswlib 需要 C++ 编译器和 cmake
下载 Visual Studio Build Tools
并确保勾选 C++ 编译器和 CMake。
4.代码实践增、删、改、查
import chromadb
chroma_client = chromadb.HttpClient(host='localhost', port=8000)
chroma_client.heartbeat
##创建一个集合、类似于传统数据库的表
collection = chroma_client.get_or_create_collection(name ="test_collection")
##插入数据
collection.add(
embeddings=[[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]], #向量数据
metadatas=[{"name": "item1"}, {"name": "item2"}],#元数据,描述向量的数据
ids=["id1", "id2"]
)
##删除数据
collection.delete(
ids=["id1"]
)
##更新数据
collection.update(
ids=["id1", "id2", ],
embeddings=[[1.1, 2.3, 3.2], [4.5, 6.9, 4.4]],
metadatas=[{"chapter": "3", "verse": "16"}, {"chapter": "3", "verse": "5"}],
documents=["doc1", "doc2"],
)
# 查询数据
results = collection.get(
where={"verse": "5"}
)
print(results)
# 查询数据
results = collection.query(
query_embeddings=[1.0, 2.0, 3.0],
where={"verse": "16"}
)
#删除集合
chroma_client.delete_collection("test_collection")