一、什么是 Chroma?

Chroma是一个 本地运行的开源向量数据库,专为 AI 应用场景设计,比如文档检索、RAG(Retrieval-Augmented Generation)等。它支持嵌入向量的存储与检索,可以和 OpenAI、LangChain 等无缝集成。

二、安装 Chroma

你可以通过 pip 安装 Chroma 的 Python 客户端:

pip install chromadb

注意:Chroma 默认使用本地嵌入式数据库,不依赖外部服务。

三、快速上手

1. 初始化 Chroma 客户端

import chromadb
from chromadb.config import Settings

client = chromadb.Client(Settings(
    chroma_db_impl="duckdb+parquet",  # 使用默认本地存储
    persist_directory="./chroma_db"   # 数据保存路径
))

2. 创建集合(Collection)

collection = client.create_collection(name="my_collection")

集合是向量数据的容器,相当于数据库中的“表”。

3. 插入数据

collection.add(
    documents=["今天天气真好", "人工智能正在改变世界"],
    metadatas=[{"source": "note1"}, {"source": "note2"}],
    ids=["doc1", "doc2"]
)
  • documents: 文本数据,会自动进行嵌入(默认使用 SentenceTransformer 模型)
  • metadatas: 自定义的元信息(可用于过滤)
  • ids: 文档唯一标识符

4. 查询相似文本

results = collection.query(
    query_texts=["天气怎么样"],
    n_results=2
)

print(results)

输出格式如下:

{
  'ids': [['doc1']],
  'documents': [['今天天气真好']],
  'distances': [[0.12]]
}

distances 表示相似度(越小越接近)。

5. 使用 Embedding 向量查询(可选)

你也可以使用预计算好的向量:

# 假设你已有向量
vector = [0.1] * 768

results = collection.query(
    query_embeddings=[vector],
    n_results=2
)

6. 持久化数据

Chroma 默认将数据保存在内存中。如果你启用了 persist_directory,可以通过以下命令保存:

client.persist()

下次启动时只需重新连接目录即可:

client = chromadb.Client(Settings(persist_directory="./chroma_db"))
collection = client.get_collection("my_collection")

四、删除和更新数据

删除文档

collection.delete(ids=["doc1"])

更新文档(先删后增)

collection.update(
    ids=["doc2"],
    documents=["AI 正在迅速发展"]
)

五、配合 LangChain 使用(进阶)

Chroma 支持和 LangChain 无缝集成,适合构建 RAG 系统:

from langchain.vectorstores import Chroma
from langchain.embeddings.openai import OpenAIEmbeddings

embedding = OpenAIEmbeddings()

vectordb = Chroma(
    persist_directory="./chroma_db",
    embedding_function=embedding
)

六、总结

操作 方法
创建集合 client.create_collection()
添加文档 collection.add()
查询文档 collection.query()
删除文档 collection.delete()
更新文档 collection.update()
数据持久化 client.persist()

七、参考资源

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐