Truy vấn và cập nhật cơ sở dữ liệu

Nhập môn Embeddings với OpenAI API

Emmanuel Pire

Senior Software Engineer, DataCamp

Truy vấn cơ sở dữ liệu

Truy vấn "movies where people sing a lot" được đưa vào mô hình embedding, tính khoảng cách cosine, và lưu kết quả cuối.

Nhập môn Embeddings với OpenAI API

Truy vấn cơ sở dữ liệu

Truy vấn được đưa trực tiếp vào vector database để tạo embedding; database đã có tài liệu đã được embed.

Nhập môn Embeddings với OpenAI API

Lấy collection

from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction

collection = client.get_collection(
    name="netflix_titles", 
    embedding_function=OpenAIEmbeddingFunction(api_key="...")
)
  • Phải chỉ định cùng embedding function đã dùng khi thêm dữ liệu vào collection
Nhập môn Embeddings với OpenAI API

Truy vấn 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]]
Nhập môn Embeddings với OpenAI API

query() trả về dict với nhiều khóa:

  • ids: ID các mục trả về
  • embeddings: Embedding của các mục trả về
  • documents: Văn bản nguồn của các mục trả về
  • metadatas: Metadata của các mục trả về
  • distances: Khoảng cách từ văn bản truy vấn
{'ids': [...],
 'embeddings': None,
 'documents': [...],
 'metadatas': [...],
 'distances': [...]}
Nhập môn Embeddings với OpenAI API

Văn bản truy vấn được làm nổi bật cùng với id của ba kết quả truy vấn tạo ra.

  • Danh sách đầu tương ứng với query_text đầu
  • Nhiều query_text sẽ trả về nhiều danh sách
Nhập môn Embeddings với OpenAI API

Các ID của kết quả truy vấn được làm nổi bật cùng tài liệu, metadata và khoảng cách của chúng.

Nhập môn Embeddings với OpenAI API

Cập nhật collection

collection.update(
  ids=["id-1", "id-2"],
  documents=["New document 1", "New document 2"]
)
  • Chỉ bao gồm các trường cần cập nhật, trường khác giữ nguyên
  • Collection sẽ tự động tạo embeddings
Nhập môn Embeddings với OpenAI API

Upsert collection

collection.upsert(
  ids=["id-1", "id-2"],
  documents=["New document 1", "New document 2"]
)
  • Thiếu ID → thêm mới
  • Có ID → cập nhật
Nhập môn Embeddings với OpenAI API

Xóa

Xóa mục khỏi collection

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

 

Xóa toàn bộ collections và mục

client.reset()
  • Cảnh báo: thao tác này sẽ xóa toàn bộ trong cơ sở dữ liệu!
Nhập môn Embeddings với OpenAI API

Ayo berlatih!

Nhập môn Embeddings với OpenAI API

Preparing Video For Download...