执行相似度查询
使用 pgvector 运算符执行基础向量相似度查询,在数据中查找最近邻。
执行相似度查询 是 CoddyKit 上的免费 Vector Databases: Pinecone, Weaviate & pgvector 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Vector Databases: Pinecone, Weaviate & pgvector 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Vector Databases: Pinecone, Weaviate & pgvector 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Unlocking Similarity Queries
Welcome! In this lesson, we'll dive into one of the most powerful features of vector databases: similarity queries.
You'll learn how to ask your database to find items that are 'similar' to a given item, based on their vector embeddings.
Why Similarity Matters
Similarity queries are at the heart of many AI applications:
- Recommendation Systems: Find products similar to what a user liked.
- Semantic Search: Retrieve documents with similar meaning, not just keyword matches.
- Anomaly Detection: Identify data points that are unusually 'far' from others.
They help us make sense of high-dimensional data.
Measuring Vector Distance
How do we define 'similarity' for vectors? We use distance metrics.
Imagine vectors as points in space. The 'closer' two points are, the more similar their underlying data is. Different metrics measure this distance in different ways.
Euclidean Distance (L2 Norm)
Euclidean distance, also known as L2 distance, is the most intuitive metric. It's the straight-line distance between two points in a Euclidean space.
In pgvector, you use the <-> operator to calculate Euclidean distance. A smaller value means higher similarity.
Cosine Similarity / Distance
Cosine similarity measures the cosine of the angle between two vectors. It tells you if vectors are pointing in roughly the same direction, regardless of their magnitude (length).
pgvector uses the <#> operator for cosine distance. Cosine distance is 1 - cosine_similarity. A smaller cosine distance (closer to 0) means the vectors are more aligned and similar.
Preparing Our Data for Queries
To demonstrate queries, let's set up a simple table with some 3-dimensional vectors. This ensures our code snippets are runnable.
CREATE EXTENSION IF NOT EXISTS vector;
DROP TABLE IF EXISTS items;
CREATE TABLE items (
id serial PRIMARY KEY,
embedding vector(3)
);
INSERT INTO items (embedding) VALUES ('[1,2,3]');
INSERT INTO items (embedding) VALUES ('[1.1,2.1,3.1]');
INSERT INTO items (embedding) VALUES ('[10,20,30]');
INSERT INTO items (embedding) VALUES ('[0.9,1.9,2.9]');
INSERT INTO items (embedding) VALUES ('[1.2,2.2,3.2]');Euclidean Distance Query Example
Now, let's find the 3 items whose embeddings are closest to [1,2,3] using Euclidean distance.
Notice the <-> operator in action!
SELECT
id,
embedding,
embedding <-> '[1,2,3]' AS euclidean_distance
FROM items
ORDER BY euclidean_distance
LIMIT 3;Interpreting Euclidean Results
When you run the query, you'll see a euclidean_distance column. The items with the smallest distance values are the most similar to your query vector [1,2,3].
For example, [1.1,2.1,3.1] should have a very small Euclidean distance, indicating high similarity.
Cosine Distance Query Example
Next, let's perform a similarity search using cosine distance. We'll again query for items similar to [1,2,3].
Observe the <#> operator. Remember, it returns cosine distance, where lower values mean higher similarity.
SELECT
id,
embedding,
embedding <#> '[1,2,3]' AS cosine_distance
FROM items
ORDER BY cosine_distance
LIMIT 3;Interpreting Cosine Results
The cosine_distance column shows how aligned the vectors are. A value close to 0 means the vectors point in almost the same direction (very similar).
A value close to 2 means they point in opposite directions (very dissimilar). Values near 1 mean they are orthogonal.
Choosing the Right Metric
Which metric should you use?
- Euclidean distance is great when the magnitude (length) of the vector is important.
- Cosine similarity/distance is preferred when only the direction of the vector matters, not its length. This is common for text embeddings where vector length might vary but direction captures semantic meaning.
Quick Check: Operators
You've learned about two key pgvector operators for similarity queries. Let's test your knowledge!
Recap: Similarity Queries
Great job! You've learned how to perform similarity queries with pgvector.
- We use distance metrics to quantify similarity.
- Euclidean distance (
<->) measures straight-line distance. - Cosine distance (
<#>) measures the angle between vectors. - Choosing the right metric depends on whether vector magnitude or direction is more relevant for your data.
常见问题解答
「执行相似度查询」课时是免费的吗?
是的 — 「执行相似度查询」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Vector Databases: Pinecone, Weaviate & pgvector 课程的其余内容,请升级到 CoddyKit PRO。 Vector Databases: Pinecone, Weaviate & pgvector 课程共包含 4 节课。
「执行相似度查询」这节课中我会学到什么?
使用 pgvector 运算符执行基础向量相似度查询,在数据中查找最近邻。 你通过在浏览器中直接运行的动手代码来练习 Vector Databases: Pinecone, Weaviate & pgvector,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Vector Databases: Pinecone, Weaviate & pgvector 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Vector Databases: Pinecone, Weaviate & pgvector 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「执行相似度查询」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Vector Databases: Pinecone, Weaviate & pgvector 课中编写并运行代码吗?
能。每节 Vector Databases: Pinecone, Weaviate & pgvector 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。