16 min read
Embeddings and semantic search with pgvector
In one sentence: An embedding turns a text into a list of numbers, a point, so that texts that mean the same thing end up close together. The shop stores each product's embedding in PostgreSQL with pgvector, and “something for the cold” finds the hoodie, the blanket and the scarf even though they don't share a single word.
What you will learn
- Explain what an embedding is and why cosine distance measures how alike two texts are.
- Store vectors in PostgreSQL with pgvector and find the nearest ones with <=> and an HNSW index, knowing that it's approximate.
- Compute the vectors in the worker, through the outbox, and combine searching by words with searching by meaning.
- Decide when searching by words is enough, and measure what the model costs in memory.
Before you start, read: 04-mcp.md phase-5/07-indexes.md phase-9/07-events.md
The problem
Section titled “The problem”Imagine that Carmen writes to the assistant: “do you have something for the cold?” search_products, the tool from lesson 3, looks for products whose name contains “something for the cold”. There are none.
And the shop sells a scarf, gloves, a wool hat and a blanket. The words don’t match; the meaning does. Searching by words finds words, and people ask for what they need.
Phase 5 promised pgvector for Phase 11, the PostgreSQL extension that searches by similarity of meaning. Here the shop uses it for Semantic searchSearching by what the question means, not by its words: the question and what’s searched are turned into embeddings, and the nearest come out. It always returns something, even if it’s no use, so each result carries its distance.Go to definition: searching by what the question means, not by its words.
The analogy
Section titled “The analogy”The analogy
In a supermarket, things are placed by what they are: one aisle for winter clothes, another for the beach. You ask for “something for the cold,” and they take you to the winter aisle, even though no sign says “cold.”
An embedding gives each product its place in a huge supermarket, arranged by what it means. Your question gets a place too, and the nearest products are the answer.
Where the analogy breaks down
- A supermarket has two dimensions. An embedding has hundreds (the shop’s, 384), and none of them means something you can name, like “warm clothes.”
- To the model, “cold” and “hot” talk about the same thing, the temperature: you’ll see a hand fan among the things for the cold.
- In a supermarket you may hear “we don’t have that.” Here there’s always a nearest product.
How it really works
Section titled “How it really works”An embedding: a text turned into 384 numbers
Section titled “An embedding: a text turned into 384 numbers”This is how the scarf’s vector starts, just as PostgreSQL stores it:
[-0.018350273,0.04371399,-0.013365716,0.08882029,0.05043198,They’re the first numbers of a list of 384: the EmbeddingA piece of text turned into a list of numbers, a vector, by a model trained so that texts that mean the same thing give nearby vectors. It’s used to search by meaning: “something for the cold” lands near a scarf even though they share no words.Go to definition of “Scarf. Long, soft and cosy scarf of thick wool, for winter days.” A vector, which you can picture as a point in a space of 384 dimensions.
A model computes it, trained so that two texts that mean the same thing give nearby points. It doesn’t write text, like the assistant’s: it turns text into numbers. From each product, it turns its name and its description:
// What becomes a product's vector: its name and, if it has one, its description. The rest (the// price, the stock) doesn't say what it's about.export function productText(product: { name: string; description: string | null }): string { return product.description ? `${product.name}. ${product.description}` : product.name;}That’s why products now have a description, and the catalog goes from 4 to 20: warm clothes, coffee, summer and gifts.
Close means similar: cosine distance
Section titled “Close means similar: cosine distance”Picture each vector as an arrow that starts from the same spot: two texts about the same thing point the same way. Cosine distanceHow far apart two vectors are by the angle between them, regardless of their length: 0 if they point the same way, 1 if they have nothing to do with each other and 2 if they point in opposite directions. Between two embeddings, it says how alike two texts are. In pgvector, it’s the <=> operator.Go to definition measures the angle between the arrows, not how long they are:
| Distance | The arrows | The texts |
|---|---|---|
| 0 | Point exactly the same way | Mean the same |
| 1 | Form a right angle | Have nothing to do with each other |
| 2 | Point in opposite directions | Almost never happens |
On November 21, 2026, on the author’s Mac, these were the five products nearest to “something for the cold”:
| Rank | Product | Distance |
|---|---|---|
| 1 | Hoodie | 0.477 |
| 2 | Blanket | 0.492 |
| 3 | Scarf | 0.514 |
| 4 | Wool hat | 0.529 |
| 5 | Hand fan | 0.547 |
None has “cold” in its name. The model gives vectors of length 1, and the math is short: 1 minus the sum of multiplying them number by number:
// Cosine distance between two vectors of length 1: 1 minus their dot product (the sum of// multiplying them number by number). The same as pgvector's <=> computes.const distance = (a: number[], b: number[]) => 1 - a.reduce((sum, x, i) => sum + x * b[i]!, 0);A small model, on your computer
Section titled “A small model, on your computer”The Claude API doesn’t compute embeddings: its documentation points to Voyage AI, by MongoDB, with another account. The shop uses a small model on your computer, with Transformers.js: free, with no internet once downloaded, in English and in Spanish.
// How many numbers each vector has: the ones the model gives. The products.embedding column is// vector(384) (migration 014): with another model, giving another number, both would have to change.export const DIMENSIONS = 384;
// The model, on Hugging Face (huggingface.co, where open models are published): a version of// paraphrase-multilingual-MiniLM-L12-v2 prepared for Transformers.js. We chose it by measuring// (2026-11-20): of the small ones that understand Spanish and English, the one that ranked the// catalogue best.export const EMBEDDING_MODEL = 'Xenova/paraphrase-multilingual-MiniLM-L12-v2';
// And its exact version: a commit of its repository on Hugging Face (the one of 2025-07-22, the// latest when we chose it). Without it the newest one (main) is downloaded, and if someone changed// its files, the new vectors would stop being comparable with the ones already stored, with nothing// to warn about it. As with package.json's exact versions, changing it is a decision, and then all// the vectors have to be computed again: npm run embeddings -- --all.export const EMBEDDING_REVISION = '2c4055b12046f11709e9df2c122e59ffbdc2f900';
// What the shop needs from an embedding model: texts in, one vector per text out, in the same// order. With this, the rest of the shop doesn't know which model is behind it, and the tests put// in a fake one (test/fake-embedder.ts) that downloads nothing and answers at once.export interface Embedder { vectors(texts: string[]): Promise<number[][]>;}EMBEDDING_MODEL: an open model, from Hugging Face. We chose it by measuring: the first one we tried put the sun cap first for “algo para el frío,” the same question in the Spanish shop.DIMENSIONS = 384: the database column must have the same number.EMBEDDING_REVISION: its exact version. With another one, the new vectors couldn’t be compared with the stored ones, and nothing would warn you.Embedder: texts in, vectors out. The tests use a fake one.
The model is loaded the first time someone asks for a vector:
// import() here, and not at the top: the library weighs too (onnxruntime, the engine that runs// the model), and this way it's only loaded if needed.const { env, pipeline } = await import('@huggingface/transformers');env.cacheDir = folder;// feature-extraction: from the text, its "features", a vector for each piece of a word.// modelSource: the folder with the files, with no internet, or, if one is missing, the name on// Hugging Face: then it downloads them into env.cacheDir, and next time they're there.// q8: the model's weights stored with 8 bits instead of 32, four times smaller and almost as// good.// revision: the exact version above, the one downloaded (from the folder it isn't needed: its// files are already that version's).const extractor = await pipeline('feature-extraction', modelSource(folder), { dtype: 'q8', revision: EMBEDDING_REVISION,});import()inside the function: a process that never searches by meaning doesn’t load the library.env.cacheDir: where the files go. In Compose, a Volume (in Docker)A folder Docker keeps outside the containers and mounts inside the ones that ask for it. What’s written to it survives when the container is deleted, so that’s where the data you need to keep goes, like a database’s.Go to definition,models, shared by the API and the worker.modelSource: if the files are already in that folder, it loads them from there without asking anyone; if one is missing, it downloads them. That’s how it works with no internet after the first time.dtype: 'q8': each of the model’s numbers in 8 bits instead of 32: four times smaller, and almost as good.
Measured on the author’s Mac: 135 MB to download, about 30 seconds the first time, under one after that and about 3 ms per text. The image doesn’t carry the model; with the library, it grows from 580 to 669 MB.
pgvector: vectors inside PostgreSQL
Section titled “pgvector: vectors inside PostgreSQL”pgvector adds a type to PostgreSQL, vector, with its distance operators and its indexes. It comes in the pgvector/pgvector image, in both Compose files:
db: image: pgvector/pgvector:0.8.7-pg18-trixie@sha256:ab49524d18df7200b74ac9a475e1db6297fc1eb57da4c214c63d10ecc4b754fa # The image creates the user and the database the first time it starts with the volume empty. environment: POSTGRES_USER: shop POSTGRES_DB: shop POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is missing in .env (see .env.example)} # The data, in a named volume: it survives docker compose down (not down -v). volumes: - data:/var/lib/postgresql # Healthy when it accepts connections: until then, whoever depends on it waits. healthcheck: test: ['CMD', 'pg_isready', '-U', 'shop', '-d', 'shop'] interval: 2s timeout: 5s retries: 15It’s PostgreSQL 18 with the extension inside. Migration 014 turns it on and adds two columns:
-- pgvector, the PostgreSQL extension to store vectors and find the nearest ones: it brings the-- vector type, the distance operators (<=>, the cosine one) and HNSW indexes. It comes installed in-- the pgvector/pgvector image (compose.yaml), and this turns it on in this database. Turning it on-- is a superuser's job: in Compose the shop user is one (the image creates it that way); in your-- own PostgreSQL, turn it on yourself once, as a superuser (the README explains how). IF NOT-- EXISTS: if it's already there, it does nothing.CREATE EXTENSION IF NOT EXISTS vector;-- The description, in free text, and the vector. Both accept NULL and have no DEFAULT: PostgreSQL-- only notes that they exist, without touching the rows already there. vector(384): exactly 384-- numbers, the ones the model gives; one with another number of dimensions doesn't fit. NULL means-- "not computed yet": the worker computes it when a product changes, or npm run embeddings, for the-- ones that were already there.ALTER TABLE products ADD COLUMN description text;ALTER TABLE products ADD COLUMN embedding vector(384);vector(384): exactly 384 numbers.NULLmeans “not computed yet”: the worker computes it, further down.
To search, the <=> operator, cosine distance. The most similar to the scarf, with no model at all:
SELECT name, embedding <=> (SELECT embedding FROM products WHERE name = 'Scarf') AS distanceFROM productsWHERE name <> 'Scarf'ORDER BY distanceLIMIT 5;In the shop, the same idea is written with Drizzle:
const nearest = await db .select({ ...columns, distance }) .from(products) .where( and( isNotNull(products.embedding), alreadyIn.length > 0 ? notInArray(products.id, alreadyIn) : undefined, ), ) .orderBy(distance) .limit(NEAREST);distance is <=> with the query’s vector (cosineDistance), and alreadyIn, the ones that already came up by name (you’ll see why soon). ORDER BY the distance and LIMIT 5: the five nearest neighbors. Without an index, PostgreSQL computes the distance to every row.
HNSW: jumping from neighbor to neighbor
Section titled “HNSW: jumping from neighbor to neighbor”With 20 products, it costs nothing; with a million, it does. Phase 5’s B-tree is no use: 384 numbers together have no order. The shop uses an HNSWHNSW stands for Hierarchical Navigable Small World.An index to find the vectors nearest to a given one without reading the whole table: a graph in floors in which the search jumps from neighbor to neighbor until it gets close. It’s approximate: much faster than reading the whole table, but it doesn’t guarantee finding the truly nearest ones.Go to definition index (Hierarchical Navigable Small World), a graph:
- At the bottom, a floor with every vector, each linked to its close neighbors.
- Above, floors with fewer and fewer vectors, linked to farther neighbors.
- To search, it enters at the top and jumps to the neighbor closest to the question until none is closer. It goes down a floor and repeats. At the bottom, it gathers the best candidates.
Like a car trip: highway, road, street. Migration 014 creates it:
-- An HNSW index (Hierarchical Navigable Small World): a graph in which each vector is linked to a-- few of its neighbours, on several floors. To find the nearest ones to a question, it goes in at-- the top and keeps jumping towards the ones that look more alike, without looking at the whole-- table. It's approximate: it almost always gives the true nearest ones, but doesn't promise it, and-- in exchange it's much faster with many rows. vector_cosine_ops: the index can sort by the cosine-- distance (<=>), the one the shop uses. Rows whose vector is NULL aren't in it.CREATE INDEX products_by_embedding ON products USING hnsw (embedding vector_cosine_ops);vector_cosine_ops: for sorting by <=>.
What it costs: approximate, and measured
Section titled “What it costs: approximate, and measured”HNSW is approximate: it looks at a small part of the table, and if the path of jumps doesn’t pass near a neighbor, it misses it. hnsw.ef_search decides how many candidates it gathers (40, unless told otherwise).
scripts/many-vectors.ts measures it, like many-orders in Phase 5, with 50,000 vectors in a separate table, grouped in 500 topics, like a model’s. On the author’s Mac (Colima, 4 GB), on November 21, 2026:
| Over 20 searches for the 10 nearest | Reading the whole table | With the index (ef_search 40) |
With the index (ef_search 100) |
|---|---|---|---|
| Time per search | 18.7 ms | 0.7 ms | 0.6 ms |
| Of the true 10, it finds | 10 | 9.3 on average | 9.8 on average |
| Average distance of what it returns | 0.181 | 0.216 | 0.181 |
Its EXPLAIN ANALYZE: 22.6 ms without the index and 0.5 ms with it. Fast, and nearly all the true ones: with 40 candidates, 186 of 200; with 100, 195 of 200.
With --random, 384 random numbers with no topics, it’s the worst case: all vectors end up at almost the same distance from all others, and the graph has nothing to guide it. That day it found 24 of 200 with ef_search 40, and 54 with 100.
Building it took 11 seconds (39 with random vectors): like any Phase 5 index, you pay when you build it and on every write.
Hybrid search: names first, then meaning
Section titled “Hybrid search: names first, then meaning”An embedding model understands sentences better than lone words. Here, “mug” finds the Mug first even by meaning, at 0.226, but that’s luck: in the Spanish version of this shop, “taza” (mug) didn’t even make the five nearest. So the shop combines both searches, by words and by meaning: a hybrid search.
const [vector] = await vectors([query]);// A product with no vector gives NULL, and Drizzle doesn't pass NULL to mapWith: it stays null.const distance = cosineDistance(products.embedding, vector!).mapWith(Number);const byName = await db .select({ ...columns, distance }) .from(products) .where(withTheName(query)) .orderBy(asc(products.id)) .limit(MAX_PRODUCTS);const alreadyIn = byName.map((product) => product.id);- The query’s vector, with the same model as the products’: the only one the API computes.
- First, the products with the query in their name, including those with no vector yet (
distance: null). - Then, the five nearest, without repeats: the query from before.
The assistant and the MCP server from lesson 4 use it.
There is always a nearest neighbor
Section titled “There is always a nearest neighbor”For “something for the cold,” the fifth is the hand fan, “to cool down on hot days,” ahead of the gloves. The model understood what the question is about, the temperature, but not which way.
And it always returns five, even if none fits: vectors can’t say “there’s nothing.” That’s why each product travels with its distance and its description, so the assistant’s model looks at both before recommending. In lesson 6 you’ll see it say “I don’t know.”
The worker computes the vectors
Section titled “The worker computes the vectors”A new product, or one with a new name or description, needs a new vector. The shop doesn’t recompute it in that request: it notes it down in Phase 9’s outbox, in the change’s TransactionA group of SQL commands that the database treats as one: either all of them are saved, or none. It starts with BEGIN and ends with COMMIT, which saves it, or with ROLLBACK, which undoes all of it.Go to definition:
// Since Phase 11 (lesson 5): a new product, or one with another name or description, needs its// vector. It isn't computed here: an outbox event is saved (Phase 9, lesson 7), in the same// transaction as the change, and the worker computes it later (queue.ts). If the change is saved,// the event is too; if not, neither is. changeId: a new one each time (queue.ts, jobId).const pendingVector = (tx: Transaction, productId: number) => saveOutbox(tx, { type: 'product-vector', productId, changeId: randomUUID() });The old vector becomes NULL; meanwhile, the product comes up by name. A price change doesn’t touch the vector.
- Workerreads the product and
computes its vector with the model
The WorkerA program that does not answer user requests: it keeps taking tasks from a queue and running them. It can be the same code as your server, started with a different command.Go to definition does the job:
// A product's vector (Phase 11, lesson 5), in the worker and not in the API: computing it costs// memory (the model) and time, and whoever changes a product doesn't have to wait for it. With// SEMANTIC_SEARCH=no it isn't computed: the job counts as done, and the product stays without a// vector (NULL) until you turn it on and run npm run embeddings. If the model fails, the job fails,// and the queue tries it again, like an email that doesn't go out.async function computeVector(productId: number): Promise<void> { if (config.SEMANTIC_SEARCH === 'no') { log.info({ productId }, 'semantic search off: the vector is not computed'); return; } const saved = await saveVectors([productId]); // 0: the product doesn't exist any more, or it changed again while the vector was computed // (another job will do its own). Neither is a failure. log.info({ productId, saved: saved === 1 }, 'product vector computed');}- Why the worker: the model takes memory and time, and whoever changes a product shouldn’t have to wait for it.
- If the model fails, the queue retries the job.
- If the product changes while it’s computing,
saveVectorsdoesn’t write the old vector.
npm run embeddings computes the missing ones.
Off by default: what the model takes in memory
Section titled “Off by default: what the model takes in memory”Measured with docker stats on November 21, 2026:
| Process | Without the model | With the model loaded |
|---|---|---|
| API | 188 MiB | 566 MiB |
| Worker | 151 MiB | 532 MiB |
About 380 MiB more per process. With both loaded and Docker limited to 2 GB, when one more process started, the system killed the API for lack of memory: Exit codeThe number a program leaves when it finishes. 0 means it went well, and any other, from 1 to 255, that something failed. The shell keeps it in $?, and scripts check it to decide whether to go on.Go to definition 137. That’s why it ships off:
# Search by meaning (Phase 11, lesson 5): yes or no. With yes, the worker computes the vector of# each product that changes, search_products searches by meaning and the first search downloads the# embedding model (about 135 MB, into MODELS_DIR; with Docker Compose, into the models volume). Each# process that loads it (the API and the worker) takes about 400 MB more memory: with Docker limited# to 2 GB, as Colima is unless told otherwise, it doesn't fit. That's why this example leaves it at# no: lesson 5 asks you to give Docker 4 GB (colima start --memory 4) before setting it to yes.SEMANTIC_SEARCH=no# MODELS_DIR=./modelsWith no, the search goes by name and nobody loads the model.
When searching by words is enough
Section titled “When searching by words is enough”ILIKE '%mug%' (lesson 3) |
PostgreSQL full-text search | Embeddings | |
|---|---|---|---|
| What it finds | The exact piece, in the name | The words, with their variants (glove, gloves) | What it means, in other words or another language |
| What it misses | “mugs”, “something for coffee” | What’s asked for without those words | Codes and lone words; sometimes, the direction |
| What it needs | Nothing | A GIN index, in the same database | A model, its memory and a vector per row |
| Why each result comes up | You can see it | You can see it | You can’t: it’s a distance |
PostgreSQL’s Full-text searchSearching for words inside texts, taking their variants into account (glove, gloves) and leaving out the words that say nothing (the, for). PostgreSQL has it built in, with tsvector, tsquery and a GIN index. It finds words, not meanings.Go to definition splits each text into words, drops the ones that say nothing (“the,” “for”) and reduces each to its root. If people search by the name of what they want, or by codes, it’s enough, and it’s cheaper. Embeddings pay off when people describe what they need.
There are separate Vector databaseA database designed to store vectors, like embeddings, and find the ones nearest to a given one. There are separate ones, like Pinecone or Qdrant; PostgreSQL does it with the pgvector extension, next to the rest of the data.Go to definition, like Pinecone or Qdrant. pgvector keeps the vectors next to the products, with their transactions: for the shop, that’s plenty.
Try it
Section titled “Try it”The goal: search for “something for the cold” by name and find nothing; turn on search by meaning and find the warm clothes; find out where a new product ranks, and measure what the index saves and what it leaves out. No paid model needed.
The outputs are from Node 26, on Linux, on November 21, 2026, on a MacBook with Docker in Colima (4 GB). Your times and memory will be different; the distances, the same or nearly.
Get the step ready
Section titled “Get the step ready”The 20-product catalog only loads into an empty database. docker compose down -v deletes the volumes, and with them your orders and your keys:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/51-embeddings.tar.gztar -xzf 51-embeddings.tar.gzcp -R 51-embeddings/. shop-api/cd shop-apinpm installdocker compose down -vdocker compose up -d --build --waitnpm install brings Transformers.js: almost 500 MB. Create the price comparison site’s key and the mcp function from lesson 4 again, and one more, search:
API=$(docker compose port api 3000)docker compose exec api node scripts/create-key.ts "Price Comparison" catalogueCATALOGUE=shop_…mcp() { curl -s "http://$API/mcp" -H "Authorization: Bearer $1" -H 'Accept: application/json, text/event-stream' --json "$2"; }search() { mcp "$CATALOGUE" "$(jq -nc --arg q "$1" '{jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"search_products",arguments:{query:$q}}}')" | jq -r '.result.content[0].text'; }Put your key in CATALOGUE=. --arg q "$1" passes the query to jq, with its quotes done right.
“something for the cold” by name
Section titled ““something for the cold” by name”1. With semantic search off
search "something for the cold"What you will see:
[]No name contains “something for the cold”. If jq gives an error, remove the function’s last jq and look at what the shop answers.
2. By words, in the descriptions
docker compose exec db psql -U shop -d shop -c "SELECT name FROM products WHERE to_tsvector('english', name || ' ' || description) @@ websearch_to_tsquery('english', 'cold');"What you will see:
name----------Wool hat(1 row)Full text, no index: with 20 rows it isn’t needed. It finds the wool hat, “when it is cold,” and misses what says it another way, like the gloves, “so your hands never freeze.”
Give Docker memory and turn the search on
Section titled “Give Docker memory and turn the search on”Give Docker 4 GB. With Colima, colima stop && colima start --memory 4. In Docker Desktop, in Settings, VM resources, Advanced, Memory limit (according to its documentation, half of your computer’s by default). If you can’t, stop here.
Put SEMANTIC_SEARCH=yes in your .env and run docker compose up -d --wait: Compose sees the change and recreates the API and the worker. Then compute the catalog’s vectors in the worker, which has the model’s volume:
3. The catalog’s vectors
docker compose exec worker node scripts/embeddings.tsWhat you will see:
{"level":30,…,"model":"Xenova/paraphrase-multilingual-MiniLM-L12-v2","revision":"2c4055b12046f11709e9df2c122e59ffbdc2f900","folder":"./models","msg":"loading the embedding model"}{"level":30,…,"ms":29377,"msg":"embedding model loaded"}Vectors computed: 20, in 29.5 sAlmost all the time is the download. If it says SEMANTIC_SEARCH=no: the shop doesn't use the vectors, run docker compose up -d --wait again. If the container dies with code 137, Docker is short of memory.
The query for the products most similar to the scarf, with three decimals:
4. The products most similar to the scarf
docker compose exec db psql -U shop -d shop -c "SELECT name, round((embedding <=> (SELECT embedding FROM products WHERE name = 'Scarf'))::numeric, 3) AS distance FROM products WHERE name <> 'Scarf' ORDER BY distance LIMIT 5;"What you will see:
name | distance-------------+----------Wool hat | 0.415Blanket | 0.504Hoodie | 0.523Beach towel | 0.622Straw hat | 0.632(5 rows)Three are warm clothes, and nobody told the database what those are. The beach towel and the straw hat are things to wear or wrap yourself in too: the model groups what looks alike, even the wrong way round.
“something for the cold” by meaning
Section titled ““something for the cold” by meaning”5. With semantic search on
search "something for the cold" | jq -c '.[] | {name, distance}'What you will see:
{"name":"Hoodie","distance":0.477}{"name":"Blanket","distance":0.492}{"name":"Scarf","distance":0.514}{"name":"Wool hat","distance":0.529}{"name":"Hand fan","distance":0.547}Now yes: the warm clothes, and the hand fan, fifth, ahead of the gloves. The API loaded the model in under a second.
6. “mug”
search "mug" | jq -c '.[] | {name, distance}'What you will see:
{"name":"Mug","distance":0.226}{"name":"Moka pot","distance":0.413}{"name":"Coffee beans","distance":0.564}{"name":"Teapot","distance":0.594}{"name":"Scented candle","distance":0.677}{"name":"Hoodie","distance":0.716}The Mug comes first, by name, and the five nearest by meaning after it: six results.
A new product, found in seconds
Section titled “A new product, found in seconds”Ana, the owner, adds some wool socks. Sign in as her and create the product:
curl -s -o /dev/null -c ana.txt --json '{"email":"ana@shop.example","password":"ana-practice-2026"}' "http://$API/v2/session"curl -s -b ana.txt --json '{"name":"Wool socks","priceCents":900,"description":"Thick wool socks to keep your feet warm in winter."}' "http://$API/v2/products" | jq -c '{id, name}'7. The worker computes its vector
docker compose logs worker --no-log-prefix --since 1m | grep 'product vector' | jq -c '{productId, saved, msg}'What you will see:
{"productId":21,"saved":true,"msg":"product vector computed"}saved: true: the vector is already in its row, after the event, the relayer, the queue and the model.
Challenge: repeat step 5. Where do the socks rank, and who drops out?Show answer
Fourth, at 0.521, between the scarf and the wool hat. The hand fan drops out: now there’s one more warm product closer than it.
When you’re done, delete ana.txt, with Ana’s session.
The model, without a database
Section titled “The model, without a database”npm run check-embeddings tries the model on your computer, outside Docker, with the catalog in db/seed.sql and four questions:
8. The model, on your computer
npm run check-embeddingsWhat you will see:
> shop-api@1.0.0 check-embeddings> node --env-file=test/.env scripts/check-embeddings.ts
Model: ./modelsLoading the model and 20 vectors: 65.9 s; the 20 again, already loaded: 56 ms (3 ms each)Process memory (RSS): 185 MB before, 457 MB with the model
"something for the cold"0.477 Hoodie0.492 Blanket0.514 Scarf0.529 Wool hat0.547 Hand fan
"a gift for someone who loves coffee"0.213 Mug0.497 Coffee beans0.499 Moka pot0.606 Gift card0.607 Teapot
"something for the summer"0.491 Flip-flops0.518 Cap0.530 Hand fan0.578 Sunglasses0.606 Beach towel
"mug"0.226 Mug0.413 Moka pot0.564 Coffee beans0.594 Teapot0.677 Scented candle
Good: for "something for the cold", the first three are warm clothesIt downloads the model again, into models/, outside Git: your computer doesn’t see Docker’s volume (this time the download took longer). “something for the summer” gets all five right: it doesn’t always get the direction wrong. If it ends with Wrong: …, tell us with the link at the end.
What it takes in memory
Section titled “What it takes in memory”9. The API and the worker, with the model loaded
docker stats --no-stream --format 'table {{.Name}}\t{{.MemUsage}}'What you will see:
NAME MEM USAGE / LIMITshop-worker-1 544.9MiB / 3.813GiBshop-api-1 547.9MiB / 3.813GiBshop-redis-1 13.32MiB / 3.813GiBshop-cache-1 5.98MiB / 3.813GiBshop-db-1 41.06MiB / 3.813GiBshop-mailpit-1 8.617MiB / 3.813GiBCompare them with the table above. Your numbers will be different.
The index, with 50,000 vectors
Section titled “The index, with 50,000 vectors”10. With the index, without it, and what it gets right
docker compose exec api node scripts/many-vectors.tsWhat you will see:
50000 vectors grouped in 500 topics, in 7.3 sHNSW index, in 10.9 s
With the index:Limit (cost=647.03..656.07 rows=5 width=12) (actual time=0.430..0.451 rows=5.00 loops=1)Buffers: shared hit=537 read=5 written=5InitPlan 1 -> Index Scan using test_vectors_pkey on test_vectors test_vectors_1 (cost=0.29..8.31 rows=1 width=1544) (actual time=0.019..0.019 rows=1.00 loops=1) Index Cond: (id = 1) Index Searches: 1 Buffers: shared hit=1 read=2 written=2-> Index Scan using test_vectors_embedding_idx on test_vectors (cost=638.72..91004.00 rows=50000 width=12) (actual time=0.429..0.449 rows=5.00 loops=1) Order By: (embedding <=> (InitPlan 1).col1) Index Searches: 1 Buffers: shared hit=537 read=5 written=5Planning:Buffers: shared hit=26 read=8 dirtied=1 written=8Planning Time: 0.206 msExecution Time: 0.496 ms
Without the index:Limit (cost=11463.79..11463.80 rows=5 width=12) (actual time=22.620..22.622 rows=5.00 loops=1)Buffers: shared hit=3724 read=6279 written=94InitPlan 1 -> Bitmap Heap Scan on test_vectors test_vectors_1 (cost=4.30..8.31 rows=1 width=1544) (actual time=0.010..0.010 rows=1.00 loops=1) Recheck Cond: (id = 1) Heap Blocks: exact=1 Buffers: shared hit=3 -> Bitmap Index Scan on test_vectors_pkey (cost=0.00..4.30 rows=1 width=0) (actual time=0.007..0.007 rows=1.00 loops=1) Index Cond: (id = 1) Index Searches: 1 Buffers: shared hit=2-> Sort (cost=11455.48..11580.48 rows=50000 width=12) (actual time=22.619..22.620 rows=5.00 loops=1) Sort Key: ((test_vectors.embedding <=> (InitPlan 1).col1)) Sort Method: top-N heapsort Memory: 25kB Buffers: shared hit=3724 read=6279 written=94 -> Seq Scan on test_vectors (cost=0.00..10625.00 rows=50000 width=12) (actual time=0.049..18.898 rows=50000.00 loops=1) Buffers: shared hit=3724 read=6279 written=94Planning:Buffers: shared hit=1Planning Time: 0.067 msExecution Time: 22.644 ms
Of the true 10 nearest, over 20 searches (vectors grouped in 500 topics):reading the whole table: 200 of 200 (100%), at 0.181 on average, in 18.7 ms per searchwith the index, hnsw.ef_search = 40: 186 of 200 (93%), at 0.216 on average, in 0.7 ms per searchwith the index, hnsw.ef_search = 100: 195 of 200 (98%), at 0.181 on average, in 0.6 ms per searchPlans are read from the bottom up, as in Phase 5: an Index Scan on the HNSW index, which stops as soon as it has five, and a Seq Scan of the 50,000 rows with a Sort on top. The last lines are the table in “What it costs”: with more candidates, it gets more right. Your numbers will be different.
With --random you’ll see the worst case. Afterwards, drop it: docker compose exec api node scripts/many-vectors.ts --drop.
On your server
Section titled “On your server”.env.production.example also has SEMANTIC_SEARCH=no: on Phase 8’s 2 GB machine, leave it like that. The timer deploys the step with the pgvector image and migration 014. With memory to spare, set yes and compute the vectors: docker compose -f compose.production.yaml exec worker node scripts/embeddings.ts. Your products still have no description: give them one with PATCH /v2/products/{id}, and the worker will compute their vector.
You have already seen it
Section titled “You have already seen it”- Google Photos, when you search for “dog” or “beach” and photos nobody labeled that way show up: the same idea, with images.
- The search box of many online shops, which finds products even if you don’t type their exact name.
Common mistakes
Section titled “Common mistakes”- Comparing vectors from two models, or from two versions of the same one. Pin the version and, if you change it, recompute them all (
npm run embeddings -- --all). - Believing the search says “there’s nothing.” It always returns the nearest ones: look at the distance.
- Searching names and codes by meaning alone: hybrid search.
- Computing the vector in the request that saves the product. To the worker, through the outbox.
- Turning the search on with Docker at 2 GB. A process ends with code
137.
Summary
Section titled “Summary”- An embedding is a text turned into a vector, a point: texts that mean the same thing end up close. Cosine distance measures the angle: 0, the same; 1, nothing to do with each other.
- The shop computes it with a small model on your computer, free, with a pinned version. It takes about 380 MiB per process: that’s why the search ships off.
- pgvector stores the vectors in PostgreSQL, compares them with
<=>and indexes them with HNSW: fast, but without guaranteeing the nearest ones. - The search is hybrid, and always returns something: each result carries its distance.
- The worker computes the vectors, through the outbox. If people search by name, full-text search is enough.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- pgvector: types, operators and HNSW.
- The paper that introduced HNSW, by Malkov and Yashunin.
- Transformers.js: models in Node and in the browser.
- Full-text search, from PostgreSQL.
- Embeddings, from the Claude documentation: Voyage AI’s models.