logo
ChromaDB 向量数据库指南
AI Engineer

ChromaDB 向量数据库指南

ChromaDB 是一个开源的向量数据库,易于使用,适合快速原型开发和中小规模应用。

ChromaDB 向量数据库指南Collections

ChromaDB Collections (集合管理)

在 Chroma 中,Collection 是你存储向量、文档和元数据的地方。你可以把它理解为关系型数据库中的“表”。

#1. 集合的基本操作

#创建与获取

python
# 创建新集合,如果已存在则报错 collection = client.create_collection(name="test_name") # 如果不存在则创建,如果已存在则获取 collection = client.get_or_create_collection(name="test_name") # 仅获取已存在的集合 collection = client.get_collection(name="test_name") # 删除集合 client.delete_collection(name="test_name")

#2. 数据结构详解

当你向集合 add 数据时,可以包含以下四个部分:

  1. ids (必填): 每个项的唯一字符串标识符。
  2. embeddings (可选): 如果你自己计算了向量,传到这里。
  3. documents (可选): 原始文本。如果没传 embeddings,Chroma 会根据这些文本自动生成。
  4. metadatas (可选): 键值对字典,用于后续的精细化过滤。

#3. 更新与删除数据

python
# 更新已存在的项 collection.update( ids=["id1"], metadatas=[{"status": "archived"}], ) # Upsert (存在则更新,不存在则添加) collection.upsert( ids=["id1", "id3"], documents=["新的内容", "新添加的内容"] ) # 根据 ID 删除 collection.delete(ids=["id1"]) # 根据元数据过滤删除 collection.delete(where={"status": "archived"})

#4. 强大的过滤查询 (Where)

Chroma 支持基于元数据和文档内容的复杂过滤。

#元数据过滤 (where)

python
results = collection.query( query_texts=["查询文本"], where={"source": "notion"}, # 仅搜索来源是 notion 的数据 n_results=5 )

#文档内容过滤 (where_document)

python
results = collection.query( query_texts=["查询文本"], where_document={"$contains": "重要"} # 仅搜索包含“重要”字样的文档 )

#5. 计算距离 (Distance Metrics)

你可以选择不同的数学方法来计算“相似度”:

  • l2: 平方 L2 范数(默认)。
  • ip: 内积。
  • cosine: 余弦相似度。

在创建集合时指定:

python
collection = client.create_collection( name="my_collection", metadata={"hnsw:space": "cosine"} )

下一步:了解 Chroma 的核心——Embedding 模型自定义

相关路线图