Vector Similarity Search
establishedSummary
Store high-dimensional embedding vectors alongside records and serve approximate nearest-neighbor (ANN) queries using specialized indexes (HNSW, IVF, FAISS), enabling semantic similarity search: finding records whose meaning is close to a query, not just records whose text matches exactly.
Problem
Keyword search cannot surface semantically related content: a query for "car" does not match documents containing "automobile" unless explicitly synonymized. Vector similarity search finds semantically similar content regardless of exact keyword match, enabling RAG (Retrieval Augmented Generation), recommendation systems, semantic duplicate detection, and image similarity.
Description
Modern machine learning models (BERT, OpenAI embeddings, Cohere, etc.) can encode text, images, and structured data as dense floating-point vectors in high-dimensional space (512–3072 dimensions). Two semantically similar items produce vectors close in cosine or Euclidean distance. This enables "find items similar to this query" by encoding the query as a vector and finding the nearest neighbors in the index.
Brute-force nearest neighbor search (compare query vector against every stored vector) is O(n × d) and becomes prohibitively slow at millions of vectors. Approximate Nearest Neighbor (ANN) indexes trade a small recall loss for orders-of-magnitude faster lookup:
HNSW (Hierarchical Navigable Small World): builds a multi-layer graph where upper layers provide long-range navigation shortcuts and lower layers provide precise neighborhood traversal. Lookup time is O(log n). Used by pgvector (PostgreSQL), Weaviate, Qdrant, Chroma, and Pinecone. Very fast queries, higher memory usage.
IVF (Inverted File Index): partitions vectors into K clusters; at query time, searches only the nearest M clusters. Sub-linear lookup at the cost of reduced recall if the nearest neighbor is in an unsampled cluster. Used in FAISS, Pinecone's internal index.
PQ (Product Quantization): compresses vectors by dividing each into sub-vectors and quantizing each sub-vector to a codebook entry. Reduces memory by 8–32× at the cost of slight recall degradation. Typically combined with IVF (IVF-PQ).
pgvector (PostgreSQL extension) supports HNSW and IVF-Flat indexes natively. It is suitable for datasets up to ~10M vectors. Dedicated vector databases (Pinecone, Weaviate, Qdrant, Chroma, Milvus) handle hundreds of millions to billions of vectors with horizontal sharding and specialized storage.
With pgvector, adding vector search means enabling the extension, adding a vector column, and building an HNSW index on it:
CREATE EXTENSION vector;
ALTER TABLE documents ADD COLUMN embedding vector(1536);
CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops)
WITH (m=16, ef_construction=64);
SELECT id, content, embedding <=> $1::vector AS distance
FROM documents ORDER BY distance LIMIT 10;
The embedding pipeline has three points of contact: at write time, call an embedding API (OpenAI, Cohere) and store the resulting vector; at query time, embed the query and execute the ANN search; and on refresh, if the source document content changes, re-embed and update the stored vector. HNSW index builds are memory-intensive in pgvector; beyond roughly 10M vectors, a dedicated vector database (Pinecone, Weaviate, Qdrant, or Chroma, as managed or self-hosted options respectively) is usually the better fit.
Tradeoffs
Finds conceptually related results regardless of exact word match
Enables RAG pipelines where retrieved context must be relevant to an LLM query
Unified similarity for multimodal data (text, images, code) in the same vector space
Embedding generation adds latency at write and query time, since an embedding model must be called
ANN indexes do not guarantee returning the true nearest neighbor: recall@K is below 100%
High-dimensional vectors are memory-intensive: 1M vectors at 1536 dimensions in float32 is roughly 6 GB in memory
The vector index is a secondary artifact; when records change, embeddings must be regenerated and the index updated
Combining keyword and vector search requires reconciling scores from different ranking systems
When to use
Search queries are natural language or free-text requiring semantic understanding
Keyword-based full-text search fails for paraphrases and domain-specific synonyms
Building a RAG (Retrieval Augmented Generation) system
RAG requires finding relevant context documents semantically similar to the user's query
Recommendation system where items must be compared by content similarity
Embedding-based similarity outperforms collaborative filtering when explicit rating data is sparse
Duplicate or near-duplicate detection in large content libraries
Vectors represent content semantics; high-cosine-similarity vectors are near-duplicates
When not to use
Queries require exact keyword matching, boolean operators, or field filtering
Traditional inverted indexes (Elasticsearch, PostgreSQL full-text) are the right tool for structured keyword queries
Dataset is small (<10,000 records)
Brute-force linear scan is fast enough; ANN index overhead is not justified
Embeddings are not available or the domain is highly technical with poor embedding coverage
Low-quality embeddings produce low-quality similarity results; validate recall quality before deploying
Operational Requirements
Monitor embedding staleness
If source content is updated without re-embedding, similarity results degrade silently.
Measure recall@K for your dataset
Default HNSW parameters (m=16, ef=64) may need tuning for your data.
Batch embedding calls where possible
Embedding API cost scales with write volume.
Keep the embedding model version fixed
Different model versions produce incompatible vector spaces and require a full reindex.
Characteristics
Relationships
Complements
Basis
Vector similarity search with HNSW and IVF is documented in academic literature (Malkov & Yashunin 2018 for HNSW) and implemented in pgvector, FAISS, Pinecone, Weaviate, and Qdrant; production patterns for RAG pipelines are well established
Related Architecture Knowledge
Outbound: this entity affects
Vector search results for common queries can be cached with cache-aside to avoid repeated ANN index lookups for the same semantic query, trading some recall freshness for significant latency improvement.
Full relationship →Vector indexes must be rebuilt when embedding model versions change; stale vectors from old models mixed with new produce retrieval quality degradation.
Full relationship →Inbound: affects this entity
AI embedding lookup workloads are the primary use case for vector similarity search; nearest-neighbor retrieval over high-dimensional embedding spaces requires ANN indexes to achieve sub-second latency.
Full relationship →Qdrant is a purpose-built vector database that implements HNSW approximate nearest neighbor search with payload filtering, directly supporting the vector similarity search pattern.
Full relationship →Search-heavy workloads benefit from vector similarity search when queries require semantic matching beyond exact keyword lookup, enabling discovery of conceptually related content.
Full relationship →