You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Chroma向量库实现基于用户ID的查询过滤?

用户数据隔离实现方案(基于Chroma元数据过滤)

核心思路

给每个存入Chroma的文档添加userId元数据,查询时通过过滤该元数据,确保用户只能获取自身所属的文档内容。

具体实现步骤

1. 存入文档时添加userId元数据

在将文档存入Chroma前,为每个Document对象的metadata字段添加userId标识:

from llama_index import Document
from llama_index.vector_stores import ChromaVectorStore
from llama_index.storage.storage_context import StorageContext
import chromadb

# 初始化Chroma客户端和集合
chroma_client = chromadb.PersistentClient(path="chroma")
chroma_collection = chroma_client.get_collection("quickstart")

# 示例文档:给每个文档绑定userId
doc1 = Document(
    text="用户Alice的个人文档内容:姓名Alice,年龄30",
    metadata={"userId": "user_alice"}
)
doc2 = Document(
    text="用户Bob的个人文档内容:姓名Bob,年龄28",
    metadata={"userId": "user_bob"}
)

# 构建存储上下文并存入文档
vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents([doc1, doc2], storage_context=storage_context)

2. 查询时基于userId过滤

在构建检索器(Retriever)时,通过filter参数指定当前用户的userId,实现数据隔离:

# 假设当前登录用户是Alice,userId为"user_alice"
current_user_id = "user_alice"

# 初始化Chroma客户端和集合(和存入时一致)
chroma_client = chromadb.PersistentClient(path="chroma")
chroma_collection = chroma_client.get_collection("quickstart")

vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
index = VectorStoreIndex.from_vector_store(vector_store=vector_store)

# 构建带过滤条件的检索器
retriever = index.as_retriever(
    retriever_mode='embedding',
    filters={"userId": current_user_id}  # 关键:添加userId过滤
)

# 构建查询引擎并执行查询
query_engine = RetrieverQueryEngine(retriever)
response = query_engine.query("文档中提到的人名是什么?")
print(response)

3. 关键说明

  • 元数据格式:确保存入时的userId与查询时的过滤值完全匹配,建议用唯一标识(如用户ID字符串)。
  • 动态过滤:current_user_id可以从用户登录态中获取,实现动态的用户数据隔离。
  • 集合复用:无需为每个用户创建单独的Chroma集合,通过元数据过滤即可实现隔离,节省资源。

内容的提问来源于stack exchange,提问作者son

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 02:12:15