Article · Embeddings & vector databases · RAG
Embeddings and vector databases: searching by meaning
What an embedding is, how to compute cosine similarity, which model to pick and how to store millions of vectors in pgvector, Qdrant or Chroma – with code in Python, TypeScript, C#, Java and Go.
A customer of the pierogi place types "something without meat for a kid" into the search box and gets zero results – because the menu does not say "without meat", it says "vegetarian" and "mild". Embeddings solve this problem: they turn text into a vector of numbers so that texts with similar meaning end up close to each other. Vector databases can find the nearest neighbours among millions of such vectors in milliseconds. Together they are the foundation of semantic search and RAG.
- 1024
- vector dimensions – default in Voyage 4 models and multilingual-e5-large
- 6.1 GB
- one million 1536-dim vectors – in float32, without index and metadata
- ~4
- hits out of 40 candidates – pgvector HNSW with a filter matching 10% of rows
The problem: a search box that does not understand questions
The first version of search on Halina's Pierogi platform is a WHERE name ILIKE '%' || :q || '%' query. It works for "ruskie", but fails at everything customers describe in their own words:
| Customer types | The menu says | ILIKE result |
|---|---|---|
| "something without meat" | "vegetarian" | nothing |
| "something sweet" | "with blueberries and cream" | nothing |
| "anything with nuts?" | "walnut sauce" | nothing (different word form) |
| "ruskie pierogi" | "Ruskie pierogi" | hit |
Full-text search with stemming (for example tsvector in PostgreSQL or BM25 in Elasticsearch) helps with word forms, but it still matches words, not meaning. We need a representation in which "without meat" and "vegetarian" are close together.
Intuition: a map of meanings
Imagine a map on which every dish has coordinates. If the axes meant "vegetable/cheese", "meat" and "sweet", ruskie pierogi would sit at roughly [0.8, 0.1, 0.2] and blueberry pierogi at [0.4, 0.0, 0.9]. The question "something without meat, sweet is fine" is the point [0.9, 0.0, 0.3]. Search boils down to one question: which points lie closest to the query point?
A real embedding model does the same thing, only in hundreds or thousands of dimensions, and the axes have no human names – directions in that space emerge during training. Let's compute our toy example by hand. The cosine similarity of the query q and ruskie pierogi r:
- dot product: 0.9·0.8 + 0.0·0.1 + 0.3·0.2 = 0.78
- vector lengths: |q| = √(0.81 + 0 + 0.09) ≈ 0.949, |r| = √(0.64 + 0.01 + 0.04) ≈ 0.831
- cosine: 0.78 / (0.949 · 0.831) ≈ 0.99 – almost the same direction.
Meat pierogi score 0.14 and blueberry pierogi 0.67. The ranking is exactly what a human would expect.
Cosine similarity from scratch
import math
# Toy 3-D "embeddings": (vegetable/cheese, meat, sweet). Real ones have 384-3072 dims.
QUERY = [0.9, 0.0, 0.3] # "something without meat, sweet is fine"
DISHES = {
"ruskie pierogi": [0.8, 0.1, 0.2],
"meat pierogi": [0.1, 0.9, 0.1],
"blueberry pierogi": [0.4, 0.0, 0.9],
}
def dot(a: list[float], b: list[float]) -> float:
return sum(x * y for x, y in zip(a, b))
def norm(a: list[float]) -> float:
return math.sqrt(dot(a, a))
def cosine(a: list[float], b: list[float]) -> float:
# Angle between vectors: 1 = same direction, 0 = unrelated, -1 = opposite.
return dot(a, b) / (norm(a) * norm(b))
def l2(a: list[float], b: list[float]) -> float:
return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))
ranked = sorted(DISHES.items(), key=lambda kv: cosine(QUERY, kv[1]), reverse=True)
for name, vec in ranked:
print(f"{name:18} cos={cosine(QUERY, vec):.3f} dot={dot(QUERY, vec):.3f} l2={l2(QUERY, vec):.3f}")
# ruskie pierogi cos=0.990 dot=0.780 l2=0.173
# blueberry pierogi cos=0.674 dot=0.630 l2=0.781
# meat pierogi cos=0.139 dot=0.120 l2=1.221// Toy 3-D "embeddings": (vegetable/cheese, meat, sweet). Real ones have 384-3072 dims.
const query = [0.9, 0.0, 0.3];
const dishes: Record<string, number[]> = {
"ruskie pierogi": [0.8, 0.1, 0.2],
"meat pierogi": [0.1, 0.9, 0.1],
"blueberry pierogi": [0.4, 0.0, 0.9],
};
const dot = (a: number[], b: number[]) => a.reduce((sum, x, i) => sum + x * b[i], 0);
const norm = (a: number[]) => Math.sqrt(dot(a, a));
const cosine = (a: number[], b: number[]) => dot(a, b) / (norm(a) * norm(b));
// Normalize once at write time - then cosine == dot product (cheaper at query time).
const normalize = (a: number[]) => {
const n = norm(a);
return a.map((x) => x / n);
};
const q = normalize(query);
const ranked = Object.entries(dishes)
.map(([name, vec]) => ({ name, cos: cosine(query, vec), dotOfUnit: dot(q, normalize(vec)) }))
.sort((a, b) => b.cos - a.cos);
for (const r of ranked) {
console.log(`${r.name.padEnd(18)} cos=${r.cos.toFixed(3)} dot(unit)=${r.dotOfUnit.toFixed(3)}`);
}using System.Numerics.Tensors;
// Toy 3-D "embeddings": (vegetable/cheese, meat, sweet). Real ones have 384-3072 dims.
float[] query = [0.9f, 0.0f, 0.3f];
var dishes = new Dictionary<string, float[]>
{
["ruskie pierogi"] = [0.8f, 0.1f, 0.2f],
["meat pierogi"] = [0.1f, 0.9f, 0.1f],
["blueberry pierogi"] = [0.4f, 0.0f, 0.9f],
};
foreach (var (name, vec) in dishes.OrderByDescending(d => Cosine(query, d.Value)))
{
// TensorPrimitives uses SIMD - use it in production instead of a hand-written loop.
float fast = TensorPrimitives.CosineSimilarity(query, vec);
Console.WriteLine($"{name,-18} cos={Cosine(query, vec):F3} simd={fast:F3}");
}
static float Cosine(float[] a, float[] b)
{
float dot = 0, na = 0, nb = 0;
for (int i = 0; i < a.Length; i++)
{
dot += a[i] * b[i];
na += a[i] * a[i];
nb += b[i] * b[i];
}
return dot / (MathF.Sqrt(na) * MathF.Sqrt(nb));
}import java.util.Comparator;
import java.util.Map;
public class Similarity {
static double dot(double[] a, double[] b) {
double sum = 0;
for (int i = 0; i < a.length; i++) sum += a[i] * b[i];
return sum;
}
static double cosine(double[] a, double[] b) {
return dot(a, b) / (Math.sqrt(dot(a, a)) * Math.sqrt(dot(b, b)));
}
public static void main(String[] args) {
// Toy 3-D "embeddings": (vegetable/cheese, meat, sweet).
double[] query = {0.9, 0.0, 0.3};
Map<String, double[]> dishes = Map.of(
"ruskie pierogi", new double[]{0.8, 0.1, 0.2},
"meat pierogi", new double[]{0.1, 0.9, 0.1},
"blueberry pierogi", new double[]{0.4, 0.0, 0.9});
dishes.entrySet().stream()
.sorted(Comparator.comparingDouble(
(Map.Entry<String, double[]> e) -> cosine(query, e.getValue())).reversed())
.forEach(e -> System.out.printf("%-18s cos=%.3f%n", e.getKey(), cosine(query, e.getValue())));
}
}package main
import (
"fmt"
"math"
"sort"
)
func dot(a, b []float64) float64 {
var s float64
for i := range a {
s += a[i] * b[i]
}
return s
}
func cosine(a, b []float64) float64 {
return dot(a, b) / (math.Sqrt(dot(a, a)) * math.Sqrt(dot(b, b)))
}
func main() {
// Toy 3-D "embeddings": (vegetable/cheese, meat, sweet).
query := []float64{0.9, 0.0, 0.3}
dishes := map[string][]float64{
"ruskie pierogi": {0.8, 0.1, 0.2},
"meat pierogi": {0.1, 0.9, 0.1},
"blueberry pierogi": {0.4, 0.0, 0.9},
}
names := make([]string, 0, len(dishes))
for n := range dishes {
names = append(names, n)
}
sort.Slice(names, func(i, j int) bool {
return cosine(query, dishes[names[i]]) > cosine(query, dishes[names[j]])
})
for _, n := range names {
fmt.Printf("%-18s cos=%.3f\n", n, cosine(query, dishes[n]))
}
}Three distance measures
| Measure | Formula (intuition) | When |
|---|---|---|
| Cosine similarity | the angle between vectors, from −1 to 1 | the default for text – ignores vector length |
| Dot product | the sum of coordinate products | when vectors are normalized to length 1 – same ranking as cosine, but cheaper |
| Euclidean distance (L2) | the length of the segment between points | when the model was trained for L2; for normalized vectors the ranking matches cosine |
The key sentence: for vectors of length 1, all three measures give the same ranking. OpenAI and Voyage models already return normalized vectors; with open models you turn normalization on yourself (for example normalize_embeddings=True in sentence-transformers). In pgvector they map to the operators <=> (cosine distance, i.e. 1 − similarity), <#> (negative inner product) and <-> (L2).
How the model knows what is similar
An embedding model is usually an encoder transformer: it reads the whole text and averages its token vectors (or takes the vector of a special token) into a single vector. Quality comes from contrastive training: the model sees millions of "question – matching passage" pairs and learns to pull their vectors together and push them away from non-matching passages, often deliberately chosen "hard negatives".
The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Which embedding model to choose
- Nearest neighbours: exact or fast
- Vector databases in practice
- Dimensions, memory and cost
- A short history of meaning vectors
- When vector search, and when keywords
- Pre-production checklist
- Test yourself
- What's next