0Pricing
Vector Databases: Pinecone, Weaviate & pgvector · 강의

유사도 질의 실행하기

pgvector 연산자를 사용해 기본 벡터 유사도 질의를 실행하고 데이터에서 최근접 이웃을 찾습니다.

유사도 질의 실행하기은(는) CoddyKit의 무료 Vector Databases: Pinecone, Weaviate & pgvector 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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.

자주 묻는 질문

“유사도 질의 실행하기” 강의는 무료인가요?

네 — “유사도 질의 실행하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Vector Databases: Pinecone, Weaviate & pgvector 강의 전체를 잠금 해제할 수 있습니다. Vector Databases: Pinecone, Weaviate & pgvector 강의에는 총 4개의 강의가 포함되어 있습니다.

“유사도 질의 실행하기”에서 뭘 배우나요?

pgvector 연산자를 사용해 기본 벡터 유사도 질의를 실행하고 데이터에서 최근접 이웃을 찾습니다. 브라우저에서 직접 실행하는 실습 코드로 Vector Databases: Pinecone, Weaviate & pgvector을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Vector Databases: Pinecone, Weaviate & pgvector을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Vector Databases: Pinecone, Weaviate & pgvector은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“유사도 질의 실행하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Vector Databases: Pinecone, Weaviate & pgvector 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Vector Databases: Pinecone, Weaviate & pgvector 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. pgvector 확장 기능 설정하기
  2. PostgreSQL에 벡터 저장하기
  3. 유사도 질의 실행하기
  4. pgvector에서 거리 메트릭 선택하기
← Vector Databases: Pinecone, Weaviate & pgvector(으)로 돌아가기