
include 参数仅适用于 get() 和 query() 方法,不可用于 add();调用 add() 时传入 include 会导致 TypeError。如需获取嵌入向量、元数据等完整信息,应在检索阶段通过 include 显式声明所需字段。
`include` 参数仅适用于 `get()` 和 `query()` 方法,不可用于 `add()`;调用 `add()` 时传入 `include` 会导致 `typeerror`。如需获取嵌入向量、元数据等完整信息,应在检索阶段通过 `include` 显式声明所需字段。
在 ChromaDB 中,Collection.add() 方法的作用是向集合中插入数据,其职责仅限于写入:文档、元数据、ID 和(可选)预计算的嵌入向量。它不返回任何结果,也不支持 include 参数——该参数的设计初衷是控制读取操作(即 get 或 query)中返回哪些字段,例如嵌入向量('embeddings')、原始文档('documents')、元数据('metadatas')或相似度距离('distances')。
✅ 正确用法示例:
# ✅ 添加数据(无需且不可指定 include)
collection.add(
documents=["This is a document", "This is another document"],
metadatas=[{"source": "test_source", "page": 1}, {"source": "test_source2", "page": 2}],
ids=["id1", "id2"]
# ❌ 删除 include=['...'] —— 此处会报错 TypeError
)
# ✅ 检索时按需包含字段
results = collection.get(
ids=["id1", "id2"],
include=['documents', 'metadatas', 'embeddings']
)
print("Embeddings:", results['embeddings']) # 现在可安全访问嵌入向量
# ✅ 或执行语义查询并获取多维度结果
query_result = collection.query(
query_texts=["a related topic"],
n_results=2,
include=['documents', 'metadatas', 'distances', 'embeddings']
)
print("Top match distance:", query_result['distances'][0][0])
print("Corresponding embedding shape:", len(query_result['embeddings'][0][0]))
⚠️ 注意事项:
- include 的可选值为 ['documents', 'metadatas', 'embeddings', 'distances'],超出范围会引发 ValueError;
- 'embeddings' 仅在启用了嵌入函数(或手动传入 embeddings=)且未禁用持久化时才可用;
- 若未显式指定 include,默认仅返回 ids 和 documents(get)或 ids(query),其余字段为空;
- add() 方法成功后不会触发嵌入计算延迟——ChromaDB 会在首次 query 或显式 collection.peek() 时按需生成(取决于客户端配置与嵌入模型是否就绪)。
总结:add() 是“只写”接口,专注数据注入;get()/query() 才是“可配置读取”接口。理解这一职责分离,是高效使用 ChromaDB 的关键基础。










