Embeddings and vector search

Part of the free LogicWiz Data Engineering course, Module 16: Databases for AI agents. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 14:20 on Thursday. A customer types "my parcel has not turned up" into SwiftKart's help search and gets 0 results. The assistant uses the same search, so it has nothing to read and tells her it cannot help. Nora opens the Delivery times page: "The answer is right here. Why zero?"

You'll learn to

  • Explain what an embedding is, in plain words
  • Work out cosine similarity by hand and in SQL
  • Find the top k nearest chunks in Postgres and DuckDB
  • Say when exact search stops working and an index takes over

Learn

Zero results for a real question

The help search matches letters. It looks for the words the customer typed, and no help page contains "parcel" or "turned up". The page with the answer, Delivery times, says "delivery" and "tracking".

One word before you run it. The help pages are stored in short pieces, a sentence or two each, called chunks. The search returns chunks, and Lesson 16.3 shows how the pages are cut up.

The search the help centre runs today

SELECT chunk_id, content
FROM chunks
WHERE content ILIKE '%parcel%'
   OR content ILIKE '%turned up%';

No rows. Now change parcel to delivery and run it again: three chunks appear. The answer was there all along. The customer used a different word.

Turn meaning into numbers

A person sees at once that a missing parcel is a delivery question. The search needs the same sense: match what a text means, not how it is spelled.

Here is the trick. Give every piece of text a short list of numbers that says what it is about. Then "similar meaning" becomes "similar numbers", and a database can sort by that.

Such a list is called a vector. A vector that stands for the meaning of a text is an embedding, and the program that makes it is an embedding model.

In this lesson each embedding has 4 numbers, written by hand, and each position has a label: shipping, returns, payments, product. So you can check every sum by eye.

What each text is about

Three bars split by topic: the parcel question is almost all shipping, chunk 1 about delivery times is almost all shipping too, and chunk 3 about returns is almost all returns.

Each bar is one text, split by topic. Compare the first two bars: almost the same shape, with no word in common. The third is mostly returns.

Toy embeddings for four help chunks and one question

Textshippingreturnspaymentsproduct
chunk 1: Standard delivery takes 3 to 5 business days...0.90.10.10.0
chunk 2: Track your order from the Orders page...0.80.00.00.2
chunk 3: You can return most items within 30 days...0.20.90.10.0
chunk 7: You are only charged once per order...0.00.20.90.0
question: my parcel has not turned up0.90.00.10.1

A real model learns its numbers from data and makes hundreds of them: 384, 768, 1,536 and 3,072 are common sizes. No single one has a meaning a person could name. The SQL you write is the same. Only the length of the list changes.

Do two arrows point the same way?

Now you need one number that says how alike two vectors are.

Picture each vector as an arrow from the same starting point. Two texts about the same thing give arrows that point the same way. Two unrelated texts give arrows at right angles.

The score for this is called cosine similarity. It is 1 when the arrows point the same way, 0 when they are at right angles, and below 0 when they point in opposite directions, which is rare with text. Only the direction counts. A longer arrow does not score higher.

Play with it before you calculate anything.

The nearest arrows win

Twelve SwiftKart products and help articles drawn as arrows in two dimensions; pick a question and the nearest arrows by cosine similarity are listed, a button shows the angle between them, and a category filter removes documents before ranking.

Pick a question, then press Show the angle: a small angle means a high score. This picture uses 2 numbers per text so it fits on a page. The maths is the same with 4 numbers or 1,536.

Work one score by hand

How do you get that score without drawing arrows? Three small sums.

Multiply the two vectors position by position and add the results. Then measure the length of each arrow: square its numbers, add them, take the square root. Then divide the first sum by the two lengths multiplied together.

Dividing by the lengths is what makes direction the only thing that counts. Step through it for the parcel question and chunk 1.

The parcel question against chunk 1

Five steps that compute the cosine similarity of the parcel question and chunk 1: the two vectors side by side, the four products position by position, their sum 0.82, the two lengths of 0.911, and the final score 0.988.

  1. Two lists of four numbers. The question and chunk 1, position by position. Both put most of their weight on shipping.

  2. Multiply position by position. Shipping: 0.9 × 0.9 = 0.81. Returns: 0.0 × 0.1 = 0. Payments: 0.1 × 0.1 = 0.01. Product: 0.1 × 0.0 = 0.

  3. Add the four products. 0.81 + 0 + 0.01 + 0 = 0.82. This sum is called the dot product.

  4. Measure each arrow. Square the numbers, add them, take the square root. Both vectors give sqrt(0.81 + 0.01 + 0.01) = 0.911.

  5. Divide. 0.82 / (0.911 × 0.911) = 0.988. Almost 1: the two arrows point almost the same way.

Do the same for chunk 3, the returns chunk: the dot product is 0.19, the lengths are 0.927 and 0.911, and the score is 0.19 / (0.927 × 0.911) = 0.225. It points somewhere else.

The same multiplication in SQL

SELECT u.pos,
       u.chunk_value,
       u.query_value,
       ROUND((u.chunk_value * u.query_value)::numeric, 3) AS product
FROM chunks AS c,
     unnest(c.embedding, '{0.9,0,0.1,0.1}'::FLOAT8[])
       WITH ORDINALITY AS u(chunk_value, query_value, pos)
WHERE c.chunk_id = 1
ORDER BY u.pos;

The embedding sits in a plain FLOAT8[] column, an array of numbers. unnest with two arrays walks them side by side and returns one row per position, and WITH ORDINALITY adds the position, 1 to 4. Add up the product column: 0.82, the dot product from the walkthrough.

Remember: cosine similarity is the dot product divided by the two lengths. 1 means the same direction. Length does not matter.

Score every chunk, keep the best three

Vector search is that one number, worked out for every chunk, sorted, with the best few kept. The few you keep are called the top k. Here k is 3.

You wrap the sums in a SQL function, cosine_sim, and sort by it. Because it scores every single row, this is called exact search: it can never miss the true best match.

Mind the direction of the sort. With a similarity, higher is nearer, so you sort DESC.

A cosine function, and the top 3

CREATE FUNCTION cosine_sim(a FLOAT8[], b FLOAT8[]) RETURNS FLOAT8
LANGUAGE sql IMMUTABLE AS $$
  SELECT SUM(x * y) / (SQRT(SUM(x * x)) * SQRT(SUM(y * y)))
  FROM unnest(a, b) AS u(x, y)
$$;

SELECT chunk_id,
       content,
       ROUND(cosine_sim(embedding, '{0.9,0,0.1,0.1}')::numeric, 3) AS similarity
FROM chunks
ORDER BY similarity DESC, chunk_id
LIMIT 3;

Chunks 1 and 2, the two delivery chunks, come first, with no word in common with the question. IMMUTABLE tells Postgres the same inputs always give the same output, and chunk_id breaks ties so the order is stable. The third row, chunk 12, belongs to a seller, Acme. Lesson 16.4 adds the filter that keeps sellers apart.

The same search in DuckDB

import duckdb

duckdb.sql("CREATE TABLE chunks (chunk_id INT, content VARCHAR, embedding FLOAT[4])")
duckdb.sql("""
    INSERT INTO chunks VALUES
      (1, 'Standard delivery takes 3 to 5 business days.', [0.9, 0.1, 0.1, 0.0]),
      (2, 'Track your order from the Orders page.',        [0.8, 0.0, 0.0, 0.2]),
      (3, 'You can return most items within 30 days.',      [0.2, 0.9, 0.1, 0.0]),
      (7, 'You are only charged once per order.',           [0.0, 0.2, 0.9, 0.0])
""")

question = [0.9, 0.0, 0.1, 0.1]      # "my parcel has not turned up"
rows = duckdb.execute("""
    SELECT chunk_id,
           round(array_cosine_similarity(embedding, ?::FLOAT[4])::DOUBLE, 3) AS sim
    FROM chunks
    ORDER BY sim DESC, chunk_id
    LIMIT 3
""", [question]).fetchall()
for chunk_id, sim in rows:
    print(chunk_id, sim)

The same three sums, built into DuckDB as array_cosine_similarity (and list_cosine_similarity for lists of any length). FLOAT[4] is a fixed-size array: every row must hold exactly 4 numbers, which is the promise an embedding column should make. The scores match the Postgres ones.

Three rulers, one order

Cosine is one of three rulers a vector database offers.

  • Cosine: the angle only. Cosine distance is 1 minus the similarity, so smaller means nearer.
  • Inner product, another name for the dot product: it grows when the arrows get longer.
  • Euclidean distance, also called L2: the straight-line gap between the two arrow tips.

Now stretch or shrink every vector to length 1, by dividing it by its length. That is called normalising. On normalised vectors the dot product is the cosine, and the squared L2 distance is 2 − 2 × cosine. So all three rulers put the chunks in the same order, and you can use the cheapest. Many embedding models return vectors of length 1 already.

What two million vectors weigh

Toy vectors weigh nothing. Real ones decide the size of your server.

A number stored as a 32-bit float takes 4 bytes. A real embedding of 1,536 numbers in pgvector, the Postgres extension for vectors, takes 4 × 1,536 + 8 = 6,152 bytes. SwiftKart has two million help and ticket chunks:

  • 2,000,000 × 6,152 bytes = 12.3 GB in the table.
  • A fast index keeps another copy of every vector, and it is only fast while it sits in memory.

You can store fewer bits per number. This is called quantization: half-size floats at 2 bytes a number, small whole numbers at 1 byte, or only the sign of each number at 1 bit. Each saving loses some accuracy.

Two million 1,536-number vectors, four ways

Bars comparing the storage of two million 1,536-dimension vectors: 12.3 GB as float32, 6.16 GB as float16, 3.07 GB as int8 and 0.40 GB as binary.

Each bar is the same two million vectors. The sums: 2,000,000 × 6,152 = 12.3 GB, × 3,080 = 6.16 GB, × 1,536 = 3.07 GB, × 200 = 0.40 GB (1 GB = 10^9 bytes). vector, halfvec and bit are pgvector column types. An index adds its own copy and its links on top.

How much accuracy does each saving cost? Measure it.

Take 50 questions. Find the true 10 best chunks for each with the full vectors. Search again with the smaller vectors and count how many of the true 10 come back. That share is called recall@10: 1.00 means nothing was lost.

One trick makes tiny vectors usable. Fetch 40 candidates with the small vectors, then put those 40 in order with the full ones. That is called rescoring. So quantize the index, and keep the full vectors in the table.

What each saving costs in recall

import numpy as np

rng = np.random.default_rng(42)
centres = rng.standard_normal((20, 64))
docs = centres[rng.integers(0, 20, 2000)] + 0.6 * rng.standard_normal((2000, 64))
queries = docs[:50] + 0.3 * rng.standard_normal((50, 64))
docs /= np.linalg.norm(docs, axis=1, keepdims=True)          # length 1 from here on
queries /= np.linalg.norm(queries, axis=1, keepdims=True)

a, b = queries[0], docs[0]
print("cosine", round(float(a @ b), 4), "| L2 squared", round(float(((a - b) ** 2).sum()), 4),
      "| 2 - 2 x cosine", round(float(2 - 2 * (a @ b)), 4))

def top10(q, d):
    return np.argsort(-(q @ d.T), axis=1, kind="stable")[:, :10]

exact = top10(queries, docs)
def recall(found):
    return np.mean([len(set(f) & set(e)) / 10 for f, e in zip(found, exact)])

half = docs.astype(np.float16).astype(np.float32)                   # 2 bytes a number
lo, hi = docs.min(axis=0), docs.max(axis=0)                         # int8: 1 byte a number
codes = np.round((docs - lo) / (hi - lo) * 254 - 127).astype(np.int8)
int8 = (codes + 127.0) / 254 * (hi - lo) + lo
hamming = ((queries > 0)[:, None, :] != (docs > 0)[None, :, :]).sum(axis=2)   # binary: signs only
by_bits = np.argsort(hamming, axis=1, kind="stable")
rescored = [c[np.argsort(-(docs[c] @ q), kind="stable")[:10]] for q, c in zip(queries, by_bits[:, :40])]

for name, size, found in [("float32", 256, exact), ("float16", 128, top10(queries, half)),
                          ("int8", 64, top10(queries, int8)), ("binary", 8, by_bits[:, :10]),
                          ("binary, rescore 40", 8, rescored)]:
    print(f"{name:19} {size:3} bytes  recall@10 {recall(found):.2f}")

The first line checks the three rulers: on length-1 vectors, squared L2 equals 2 − 2 × cosine. Then the bill: float16 loses nothing, int8 loses a little (0.97), signs alone lose most of it (0.37), and rescoring 40 candidates wins much of it back (0.78). The data is seeded, 2,000 vectors of 64 numbers, so the output never changes. With 1,536 numbers a binary code holds 1,536 bits instead of 64 and does much better than here: always measure on your own data.

Scoring every row stops working

Exact search compares the question with every vector:

  • 10,000 chunks × 1,536 numbers = 15 million multiplications. Milliseconds.
  • 50 million chunks × 1,536 = 77 billion multiplications, and 307 GB of vectors read, for one question.

So big collections use an index that looks at a small part of the data and accepts that it may miss a true neighbour now and then. This is approximate nearest neighbour search, or ANN.

HNSW links each vector to a few close neighbours and walks from neighbour to neighbour towards the question, like asking for directions at every corner. IVF sorts the vectors into groups when the index is built and searches only the nearest groups, like walking straight to the right shelf in a library. Lesson 16.8 opens both.

The real thing: pgvector on a Postgres server

Runs on your laptop:

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE chunks (
  chunk_id  BIGINT PRIMARY KEY,
  content   TEXT NOT NULL,
  embedding vector(4)            -- vector(1536) for a real model
);

-- An approximate (HNSW) index for cosine distance
CREATE INDEX chunks_embedding_hnsw
  ON chunks USING hnsw (embedding vector_cosine_ops);

-- <=> is cosine DISTANCE (1 - similarity): smallest first
SET hnsw.ef_search = 100;
SELECT chunk_id,
       ROUND((embedding <=> '[0.9,0,0.1,0.1]')::numeric, 3) AS distance
FROM chunks
ORDER BY embedding <=> '[0.9,0,0.1,0.1]'
LIMIT 3;
chunk_id | distance
----------+----------
        1 |    0.012
        2 |    0.015
       12 |    0.035
(3 rows)

pgvector is not installed in the browser, so this card shows a real server. <=> returns cosine distance, so the nearest chunk has the smallest number and the sort is ascending. Check one: 0.012 is 1 − 0.988, the score you worked out by hand. hnsw.ef_search is how many candidates the walk keeps: raise it and recall goes up, and so does the time. Without an index, pgvector does exact search, with perfect recall.

Two classic vector mistakes. First, the wrong sort direction: sorting similarity ascending, or pgvector's <=> descending, returns the least similar chunks, and they still read like plausible text. Similarity: highest first. Distance: lowest first. Second, mixing models: a vector from one embedding model means nothing to another. Embed the question with the same model and version as the chunks, and re-embed everything when you change models.

Numbers to remember

WhatValueGood to know
pgvector <=Cosine distance: 1 − similarityIndex operator class vectorcosineops
pgvector <The negative inner product, so ascending still means nearest firstvectoripops. The cheapest on length-1 vectors: pgvector's README recommends it there
pgvector <-Euclidean (L2) distancevectorl2ops
Bytes per rowvector 4 × D + 8, halfvec 2 × D + 8, bit D / 8 + 8halfvec since pgvector 0.7.0. bit is made with binaryquantize(). pgvector has no int8 type; most vector databases do
HNSW defaultsm = 16, efconstruction = 64, hnsw.efsearch = 40The first two go in WITH (...) when you create the index
IVFFlat settingslists: rows / 1,000 up to a million rows, sqrt(rows) above. ivfflat.probes: default 1Start probes at sqrt(lists)
Most dimensions an index takesvector 2,000, halfvec 4,000A 3,072-number model must be indexed as halfvec or bit
How an index is judgedrecall@k: of the true top k, how many the index returnedRaising efsearch or probes buys recall with time

An index only helps a query whose operator matches its operator class. Dedicated vector databases (Pinecone, Weaviate, Qdrant, Milvus) and search engines (Elasticsearch, OpenSearch) scale further than Postgres, and Databricks Vector Search and Snowflake Cortex Search build the index for you from a table. Nearly all of them use HNSW or IVF-style indexes underneath.

What changed at SwiftKart

By 16:00 the help search runs on vectors. "My parcel has not turned up" returns the two delivery chunks first, with scores 0.988 and 0.985, and the assistant answers from them. Zero results became the right page.

Nora points at the third result: chunk 12, a delivery page that belongs to a seller, Acme. Search by meaning cannot tell whose page it is. Lesson 16.4 fixes that.

First, a quieter question. Where do chunks and their embeddings come from, and what happens when someone edits an article? Lesson 16.3 builds the pipeline that keeps them fresh.

In one line

An embedding turns text into a vector, cosine similarity scores how alike two meanings are, and exact top-k scans every row while HNSW and IVF indexes trade a little recall for speed.

Interview corner

What is an embedding, and how do you compare two of them?

An embedding is a fixed-length vector a model produces for a piece of text, trained so that similar meanings get vectors pointing in similar directions. You compare them with cosine similarity: the dot product divided by the product of the lengths, from -1 to 1. Many models output normalised vectors (length 1), and then the dot product equals the cosine and is cheaper to compute.

What is the difference between exact and approximate nearest neighbour search?

Exact search scores the query against every vector, so it always finds the true top k but costs time proportional to the table. Approximate indexes such as HNSW (a layered neighbour graph) and IVF (clusters searched a few at a time) look at a small part of the data, so they are fast but can miss true neighbours. You measure that with recall@k and tune ef_search or probes.

How would you store and search embeddings in Postgres?

Install pgvector, add a vector(1536) column (matching the model's size), and create an HNSW index with the operator class for your metric, such as vector_cosine_ops. Query with ORDER BY embedding <=> $1 LIMIT k, which returns the nearest first and can use the index. Keep metadata such as tenant and dates in ordinary columns, so you can filter with plain SQL in the same query.

You have 50 million 1,536-dimension embeddings. How much memory do they need, and how would you reduce it?

As pgvector vector they take 50M × 6,152 bytes = 308 GB in the table, and an HNSW index stores another copy plus about 192 bytes of links each at m = 16: roughly 317 GB more, which has to stay in memory to be fast. An expression index on halfvec halves the index; a binary-quantized index is about 200 bytes plus links per row, around 20 GB, if I fetch several times more candidates and rescore them with the full vectors. I would measure recall@10 for each option against exact search on a sample before choosing, and consider partitioning by tenant so each index is smaller.