查詢與更新資料庫

Introduction to Embeddings with the OpenAI API

Emmanuel Pire

Senior Software Engineer, DataCamp

查詢資料庫

查詢「people sing a lot 的電影」送入嵌入模型,計算 cosine 距離,並儲存最終結果。

Introduction to Embeddings with the OpenAI API

查詢資料庫

搜尋查詢會直接送入向量資料庫產生嵌入;資料庫已含文件的嵌入。

Introduction to Embeddings with the OpenAI API

取回 collection

from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction

collection = client.get_collection(
    name="netflix_titles", 
    embedding_function=OpenAIEmbeddingFunction(api_key="...")
)
  • 必須指定與新增至 collection 時相同的嵌入函式
Introduction to Embeddings with the OpenAI API

查詢 collection

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]]
Introduction to Embeddings with the OpenAI API

query() 會回傳含多個鍵的 dict:

  • ids:回傳項目的 id
  • embeddings:回傳項目的嵌入
  • documents:回傳項目的原始文本
  • metadatas:回傳項目的中介資料
  • distances:回傳項目與查詢文本的距離
{'ids': [...],
 'embeddings': None,
 'documents': [...],
 'metadatas': [...],
 'distances': [...]}
Introduction to Embeddings with the OpenAI API

查詢文本與其產生的三筆結果 id 被標示出來。

  • 第一個清單對應第一個 query_text
  • 多個查詢文字會回傳多個清單
Introduction to Embeddings with the OpenAI API

查詢結果的 ID 及其對應的 documents、metadata、distances 被標示出來。

Introduction to Embeddings with the OpenAI API

更新 collection

collection.update(
  ids=["id-1", "id-2"],
  documents=["New document 1", "New document 2"]
)
  • 只需提供要更新的欄位,其他欄位維持不變
  • Collection 會自動產生嵌入
Introduction to Embeddings with the OpenAI API

Upsert collection

collection.upsert(
  ids=["id-1", "id-2"],
  documents=["New document 1", "New document 2"]
)
  • 若缺少 ID → 新增
  • 若已有 ID → 更新
Introduction to Embeddings with the OpenAI API

刪除

從 collection 刪除項目

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

 

刪除所有 collections 與項目

client.reset()
  • 警告:這會刪除資料庫中的一切!
Introduction to Embeddings with the OpenAI API

一起來練習吧!

Introduction to Embeddings with the OpenAI API

Preparing Video For Download...