在第 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 載入資料的腳本開始。完整的腳本在這裡。
設定資料載入
- 創建.env:
OPENAI_API_KEY=your_openai_api_key
- 更新 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
- 載入資料:
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;
- 找一本標題中帶有「Web」的書
- 取得該書的嵌入(其數學表示)
- 將此嵌入與所有其他書籍的嵌入進行比較
- 取得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中文網其他相關文章!

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

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

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

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

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

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

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

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


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

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

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SublimeText3漢化版
中文版,非常好用

WebStorm Mac版
好用的JavaScript開發工具

Dreamweaver Mac版
視覺化網頁開發工具