搜尋
首頁後端開發Python教學向量搜尋入門(第 2 部分)

Getting Started with Vector Search (Part 2)

在第 1 部分中,我們使用 pgvector 設定 PostgreSQL。現在,讓我們看看向量搜尋實際上是如何運作的。

內容

  • 什麼是嵌入?
  • 載入範例資料
  • 探索向量搜尋
  • 了解 PostgreSQL 運算子
  • 後續步驟

什麼是嵌入?

嵌入就像數位內容的智慧摘要。兩個嵌入之間的距離顯示它們的相似程度。距離小表示向量非常相似,距離大表示它們相關性較低。

? Book A: Web Development  (Distance: 0.2) ⬅️ Very Similar!
? Book B: JavaScript 101   (Distance: 0.3) ⬅️ Similar!
? Book C: Cooking Recipes  (Distance: 0.9) ❌ Not Similar

載入樣本數據

現在,讓我們用一些資料填入我們的資料庫。我們將使用:

  • 開放圖書資料的圖書館 API
  • 用於建立嵌入的 OpenAI API
  • pgvector 用於儲存和搜尋它們

專案結構

pgvector-setup/             # From Part 1
  ├── compose.yml
  ├── postgres/
  │   └── schema.sql
  ├── .env                  # New: for API keys
  └── scripts/              # New: for data loading
      ├── requirements.txt
      ├── Dockerfile
      └── load_data.py

建立腳本

讓我們從一個從外部 API 載入資料的腳本開始。完整的腳本在這裡。

設定資料載入

  1. 創建.env:
OPENAI_API_KEY=your_openai_api_key
  1. 更新 compose.yml 以新增資料載入器:
services:
  # ... existing db service from Part 1

  data_loader:
    build:
      context: ./scripts
    environment:
      - DATABASE_URL=postgresql://postgres:password@db:5432/example_db
      - OPENAI_API_KEY=${OPENAI_API_KEY}
    depends_on:
      - db
  1. 載入資料:
docker compose up data_loader

您應該會看到 10 本程式設計書籍及其元資料。

探索向量搜尋

連接到您的資料庫:

docker exec -it pgvector-db psql -U postgres -d example_db

了解向量數據

讓我們看看嵌入其實是什麼樣的:

-- View first 5 dimensions of an embedding
SELECT
    name,
    (embedding::text::float[])[1:5] as first_5_dimensions
FROM items
LIMIT 1;
  • 每個嵌入有 1536 個維度(使用 OpenAI 的模型)
  • 值的範圍通常為 -1 到 1
  • 這些數字代表語意

尋找類似的書籍

嘗試簡單的相似性搜尋:

-- Find 3 books similar to any book about Web
SELECT name, metadata
FROM items
ORDER BY embedding  (
    SELECT embedding
    FROM items
    WHERE metadata->>'title' LIKE '%Web%'
    LIMIT 1
)
LIMIT 3;
  1. 找一本標題中帶有「Web」的書
  2. 取得該書的嵌入(其數學表示)
  3. 將此嵌入與所有其他書籍的嵌入進行比較
  4. 取得3本最相似的書(距離最小)

了解 PostgreSQL 運算符

讓我們分解一下向量搜尋查詢中使用的運算子:

JSON 文字運算子:->>

從 JSON 欄位中擷取文字值。

範例:

-- If metadata = {"title": "ABC"}, it returns "ABC"
SELECT metadata->>'title' FROM items;

向量距離運算子:

測量兩個向量之間的相似性。

  • 距離越小=越相似
  • 距離越大=相似度越低

範例:

-- Find similar books
SELECT name, embedding  query_embedding as distance
FROM items
ORDER BY distance
LIMIT 3;

下一步

接下來,我們將:

  • 建立 FastAPI 應用程式
  • 建立搜尋端點
  • 透過 API 存取我們的向量搜尋

敬請關注第 3 部分:「建立向量搜尋 API」! ?

歡迎在下面留言! ?

以上是向量搜尋入門(第 2 部分)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解釋嗎?揭穿神話Python:它是真正的解釋嗎?揭穿神話May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

與同一元素的Python串聯列表與同一元素的Python串聯列表May 11, 2025 am 12:08 AM

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

解釋與編譯語言:Python的位置解釋與編譯語言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循環時:您什麼時候在Python中使用?循環時:您什麼時候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具