在第 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中文网其他相关文章!

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

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)listCompreanspearensionforcontroloverduplicates,每个methodhasdhasdifferentperferentperferentperforentperforentperforentperfortenceandordormplications。

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
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Atom编辑器mac版下载
最流行的的开源编辑器

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

Dreamweaver CS6
视觉化网页开发工具

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中