查询与更新数据库

使用 OpenAI API 的 Embeddings 入门

Emmanuel Pire

Senior Software Engineer, DataCamp

查询数据库

查询"people 唱歌很多的电影"输入到嵌入模型,计算余弦距离,并存储最终结果。

使用 OpenAI API 的 Embeddings 入门

查询数据库

将搜索查询直接送入向量数据库进行嵌入,数据库已包含嵌入后的文档。

使用 OpenAI API 的 Embeddings 入门

获取集合

from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction

collection = client.get_collection(
    name="netflix_titles", 
    embedding_function=OpenAIEmbeddingFunction(api_key="...")
)
  • 必须指定与添加数据时相同的嵌入函数
使用 OpenAI API 的 Embeddings 入门

查询集合

result = collection.query(
  query_texts=["movies where people sing a lot"],
  n_results=3
)
print(result)
{'ids': [['s4068', 's293', 's2213']],
 'embeddings': None,
 'documents': [['Title: Quién te cantará (Movie)\nDescription: When a near-...',
   'Title: Quartet (Movie)\nDescription: To save their posh retirement home, ...',
   'Title: Sing On! Spain (TV Show)\nDescription: In this fast-paced, high-...']],
 'metadatas': [[None, None, None]],
 'distances': [[0.350419282913208, 0.36049118638038635, 0.37080681324005127]]
使用 OpenAI API 的 Embeddings 入门

query() 返回一个包含多项键的字典:

  • ids:返回项的 id
  • embeddings:返回项的嵌入
  • documents:返回项的源文本
  • metadatas:返回项的元数据
  • distances:返回项与查询文本的距离
{'ids': [...],
 'embeddings': None,
 'documents': [...],
 'metadatas': [...],
 'distances': [...]}
使用 OpenAI API 的 Embeddings 入门

高亮显示了查询文本以及其生成的三个查询结果的 id。

  • 第一个列表对应第一个 query_text
  • 多个查询文本将返回多个列表
使用 OpenAI API 的 Embeddings 入门

高亮显示了查询结果的 ID 及其关联的文档、元数据和距离。

使用 OpenAI API 的 Embeddings 入门

更新集合

collection.update(
  ids=["id-1", "id-2"],
  documents=["New document 1", "New document 2"]
)
  • 只包含需更新的字段,其他将保持不变
  • 集合会自动创建嵌入
使用 OpenAI API 的 Embeddings 入门

Upsert 集合

collection.upsert(
  ids=["id-1", "id-2"],
  documents=["New document 1", "New document 2"]
)
  • 若缺少 ID → 添加
  • 若已有 ID → 更新
使用 OpenAI API 的 Embeddings 入门

删除

从集合中删除项

collection.delete(ids=["id-1", "id-2"])

 

删除所有集合与项

client.reset()
  • 警告:这将删除数据库中的所有内容
使用 OpenAI API 的 Embeddings 入门

Passons à la pratique !

使用 OpenAI API 的 Embeddings 入门

Preparing Video For Download...