跳转到主要内容

添加数据

使用 .add 向集合中插入新记录。每条记录都需要一个唯一的字符串 id
collection.add(
    ids=["id1", "id2", "id3"],
    documents=["lorem ipsum...", "doc2", "doc3"],
    metadatas=[{"chapter": 3, "verse": 16}, {"chapter": 3, "verse": 5}, {"chapter": 29, "verse": 11}],
)
您必须提供 documents(文档)、embeddings(向量)或两者兼有。metadatas(元数据)始终是可选的。当仅提供 documents 时,Chroma 将使用集合的向量化函数(embedding function)为您生成向量。 如果您已经计算了向量,请将其与 documents 一起传入。Chroma 将按原样存储两者,而不会对文档进行重新向量化。
collection.add(
    ids=["id1", "id2", "id3"],
    embeddings=[[1.1, 2.3, 3.2], [4.5, 6.9, 4.4], [1.1, 2.3, 3.2]],
    documents=["doc1", "doc2", "doc3"],
    metadatas=[{"chapter": 3, "verse": 16}, {"chapter": 3, "verse": 5}, {"chapter": 29, "verse": 11}],
)
如果您的文档存储在其他地方,您可以只添加向量和元数据。使用 ids 将记录与您的外部文档相关联。如果您的文档非常大(例如高分辨率图像或视频),这是一种很有用的模式。
collection.add(
    ids=["id1", "id2", "id3"],
    embeddings=[[1.1, 2.3, 3.2], [4.5, 6.9, 4.4], [1.1, 2.3, 3.2]],
    metadatas=[{"chapter": 3, "verse": 16}, {"chapter": 3, "verse": 5}, {"chapter": 29, "verse": 11}],
)

元数据

元数据的值可以是字符串、整数、浮点数或布尔值。此外,您还可以存储这些类型的数组。
collection.add(
    ids=["id1"],
    documents=["lorem ipsum..."],
    metadatas=[{
        "chapter": 3,
        "tags": ["fiction", "adventure"],
        "scores": [1, 2, 3],
    }],
)
数组中的所有元素必须是同一类型,且不允许为空数组。您可以使用 $contains$not_contains 运算符对数组元数据进行过滤 —— 详见元数据过滤

行为特性

  • 如果您添加的记录 ID 在集合中已存在,该操作将被忽略且不会抛出错误。为了覆盖集合中的数据,您必须使用更新(update)数据的方法。
  • 如果提供的向量维度与集合中已有向量的维度不匹配,系统将抛出异常。