🤖 AI/ML

HNSW

Hierarchical Navigable Small World

A graph-based ANN algorithm. High accuracy and fast search speed.

📖 Detailed Explanation

HNSW (Hierarchical Navigable Small World) is a graph-based algorithm that quickly finds approximate nearest neighbors (ANN) in high-dimensional vector spaces. It was published in 2016 by Yu. A. Malkov and D. A. Yashunin, and is currently one of the most widely used vector search algorithms.

HNSW is based on Small World network theory. It builds the graph in a hierarchical structure, jumping far in the upper layers and searching more precisely as it descends to the lower layers. This approach enables search with O(log N) time complexity.

The key parameters are M (the maximum number of connections per node) and ef (the number of candidates to explore during search). A larger M increases accuracy but uses more memory, and a larger ef increases search accuracy but slows down speed.

Most vector databases, including Pinecone, Weaviate, Milvus, and Qdrant, use HNSW as their default index. It can perform millisecond-level search even on more than 10 billion vectors, making it an essential technology for RAG, recommendation systems, image search, and more.

💻 Code Example

import numpy as np
import hnswlib

# HNSW 인덱스 생성 및 검색 예제
def create_hnsw_index(vectors, dim=128):
    num_elements = len(vectors)

    # HNSW 인덱스 초기화
    index = hnswlib.Index(space='cosine', dim=dim)

    # 인덱스 파라미터 설정
    # M: 노드당 연결 수 (높을수록 정확, 메모리 증가)
    # ef_construction: 인덱스 구축 시 탐색 범위
    index.init_index(
        max_elements=num_elements,
        ef_construction=200,
        M=16
    )

    # 벡터 추가
    ids = np.arange(num_elements)
    index.add_items(vectors, ids)

    # 검색 시 ef 파라미터 설정 (높을수록 정확, 느림)
    index.set_ef(100)

    return index

# 사용 예시
dim = 128
num_vectors = 100000
vectors = np.random.randn(num_vectors, dim).astype('float32')

# 인덱스 생성
index = create_hnsw_index(vectors, dim)

# 쿼리 벡터로 검색
query = np.random.randn(1, dim).astype('float32')
labels, distances = index.knn_query(query, k=10)

print(f"가장 유사한 10개 벡터 ID: {labels[0]}")
print(f"코사인 거리: {distances[0]}")

🗣️ Say It Like This in Practice

In a vector DB selection meeting

"We need to store 100 million embeddings, so an HNSW-based index is a must. Milvus and Qdrant support HNSW well, and tuning the ef and M parameters gets us recall of 95% or higher."

In a technical interview

"The difference between HNSW and IVF is structure. IVF is cluster-based and memory-efficient but has lower recall, while HNSW is graph-based and has higher recall but uses more memory. In most cases, HNSW is advantageous in terms of quality."

In a performance optimization discussion

"Our search latency is 50ms, and we need to bring it down to 10ms or less. Lowering ef from 100 to 50 makes it faster but reduces recall, so we first need to find the right trade-off through benchmarking."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

1
Memory usage

HNSW must keep its graph structure in memory. 100 million 768-dimensional vectors may require about 300GB+ of memory, so calculate the capacity in advance.

2
Index build time

Building an HNSW index on a large dataset can take several hours. Use batch insertion and parallel processing.

3
Parameter tuning required

The optimal values of the M, ef_construction, and ef parameters vary depending on the characteristics of the dataset. Be sure to tune them with your own benchmarks.

🔗 Related Terms

📚 Learn More