C.W.K.
Stream
Lesson 03 of 05 · published

HNSW vs IVFFlat: 인덱스 고르기

~22 min · pgvector, indexes, performance

Level 0Scout
0 XP0/41 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

pgvector 와 함께 ship 되는 두 인덱스

  • HNSW (Hierarchical Navigable Small World) — 그래프 기반 ANN. 높은 recall, 느린 build, incremental insert 지원. 2026년 default.
  • IVFFlat (Inverted File with Flat compression) — 파티션 기반. 빠른 build, 낮은 recall, 데이터 늘면 주기적 rebuild 필요.

파라미터 고르기

HNSW 의 두 knob 은 m (그래프 degree, default 16) + ef_construction (build effort, default 64). query 에는 SET hnsw.ef_search = 40 으로 runtime 에 recall vs latency tradeoff. IVFFlat 은 create 시점 lists + query 시점 ivfflat.probes 가 같은 역할.

여기서 'recall' 이 진짜 뭘 의미해

ANN 인덱스는 approximate. Recall 은 인덱스가 실제로 반환하는 진짜 top-k 결과의 비율. HNSW 가 default 셋팅으로 보통 0.95–0.99; 낮은 probes 의 IVFFlat 은 0.7 까지 떨어질 수 있어. 숫자 믿기 전에 항상 held-out query set 으로 exact scan 대비 recall 측정.

Code

HNSW 인덱스 생성·sql
-- Cosine
CREATE INDEX chunks_embedding_hnsw_cos
    ON chunks USING hnsw (embedding vector_cosine_ops)
    WITH (m = 16, ef_construction = 64);

-- L2
-- CREATE INDEX ... USING hnsw (embedding vector_l2_ops)    WITH (...);
-- Inner product
-- CREATE INDEX ... USING hnsw (embedding vector_ip_ops)    WITH (...);

SET hnsw.ef_search = 40;   -- 높이면 recall 높아지고 query 느려짐
Top-k cosine query·sql
-- vector_cosine_ops 의 <=> operator 는 cosine DISTANCE.
SELECT id, source, chunk_index, text, 1 - (embedding <=> $1) AS similarity
FROM   chunks
ORDER BY embedding <=> $1
LIMIT  10;

External links

Exercise

10만 row 로드. default 셋팅 HNSW 생성; query 100개 시간 재. 인덱스 drop 후 IVFFlat lists=100, probes=10 으로 시도; query 100개 시간 재. median latency + 대략 recall 비교 (인덱스 없는 ORDER BY 로 sample 의 ground truth).

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.