High-Dimensional Vector Embeddings & Similarity Math
Fixed-character chunking severs sentences mid-thought and produces incoherent vector clusters that degrade retrieval quality. This article builds the mathematical foundation — Dot Product, Cosine Similarity, and L2 distance — then implements an AST-aware semantic chunking pipeline with SHA-256 deduplication for the Workspace knowledge vault.
Full-Stack AI Architecture: From Streaming Foundations to Resilient Agentic Systems in Node.js & React
High-Dimensional Vector Embeddings & Similarity Math
Fixed-size character chunking — "split every 500 characters" — is the most common mistake in production RAG systems. It severs sentences mid-clause, breaks code blocks in the middle of function signatures, and splits Markdown headers from the content they govern. The resulting vector clusters are semantically incoherent: embeddings that encode half-ideas from two different topics.
This article builds the mathematical foundation of vector search from first principles — Dot Product, Cosine Similarity, and L2 Euclidean distance — then implements an AST-aware chunking pipeline that respects document structure, and adds SHA-256 deduplication to prevent expensive re-embedding of identical content across document revisions.
Who this is for: Full-stack engineers who understand that embeddings work but not why. After this article, you will make informed decisions about distance metrics, embedding dimensions, normalisation, and chunk boundaries — not just copy boilerplate from embedding API documentation.
1. Vector Embeddings: From Text to Geometry
1.1 What an Embedding Is
A text embedding is a function that maps a variable-length string to a fixed-length dense vector of floating-point numbers in a high-dimensional space. Semantically similar texts map to geometrically nearby vectors. The embedding model has learned this mapping from billions of text pairs during training.
1.2 The Three Distance Metrics
| Metric | Formula | When to Use |
|---|---|---|
| Dot Product | a · b = Σ(aᵢ × bᵢ) |
Normalised vectors only — fastest computation |
| Cosine Similarity | cos(θ) = (a · b) / (|a| × |b|) |
Unnormalised vectors — angle measures semantic similarity |
| L2 Euclidean | ‖a - b‖ = √Σ(aᵢ - bᵢ)² |
When magnitude (not just angle) carries meaning |
Always L2-normalise vectors at ingestion time. When ‖v‖ = 1 for all vectors, Dot Product and Cosine Similarity are identical (cos(θ) = a · b for unit vectors), and Dot Product is 3–5× faster to compute. pgvector's inner product operator <#> (negated dot product) is the fastest index scan available — but requires normalised vectors.
2. The Chunking Problem
2.1 Why Character Splits Fail
2.2 AST-Aware Semantic Chunking
The correct approach is to parse the document into its abstract syntax tree and chunk along semantic boundaries: Markdown headings, code blocks, and list items — not arbitrary character counts.
3. SHA-256 Deduplication at Ingestion
3.1 The Deduplication Problem
When a document is revised, re-uploaded, or re-indexed, naive re-embedding re-processes every chunk — even unchanged ones. At $0.00013 per 1,000 tokens (text-embedding-3-large), re-embedding a 100-page technical spec (≈200,000 tokens) costs $26 per indexing run. With daily document revisions across 1,000 workspace documents, that is a significant avoidable cost.
4. PostgreSQL Schema for Vector Storage
Summary
| Concept | Rule |
|---|---|
| L2 normalisation | Normalise at ingestion; use inner product <#> operator for 3–5× faster queries |
| AST chunking | Chunk at Markdown heading and code block boundaries — never mid-sentence |
| SHA-256 dedup | Hash-check before embedding; skip re-embedding of unchanged chunks |
| Batch embedding | Group 20 chunks per API call with concurrency limiter to avoid rate-limit spikes |
| Min chunk size | Reject chunks under 50 tokens — they carry insufficient semantic signal |
What's Next
Part 9 migrates the flat chunk table into a production HNSW index with tuned
mandef_constructionparameters, adds Row-Level Security for multi-tenant isolation, and implements the shadow-column migration strategy for zero-downtime embedding model upgrades.
This article was developed with AI-assisted deep search, specification cross-referencing, and technical research synthesis.