Courses / AI Engineering: LLMs, RAG and Agentic System Design / Chapter 5
Module 3 · Vector search and LLM applications · Chapter 5 of 24
Embeddings and vector databases
Builds on Generative AI and how LLMs work and Working with model APIs. Next up: Building LLM applications: chains, tools and memory.
Part 1 · What an embedding is
Text as a point in space
Search by meaning needs numbers to compare, so a trained model turns each piece of text into an embedding: a list of floating-point numbers, a vector, where similar meanings get vectors that lie close together. Every retrieval system in this part of the course starts here.
The vector has a fixed length whatever the text. A one-word query and a long paragraph both come back as, say, 768 numbers. That length is the model's dimensionality. Each number alone means nothing a person can read. What matters is the geometry: distances and angles between whole vectors. Two sentences that ask the same thing in different words, such as "How do I reset my password?" and "Steps to change a forgotten login password", end up near each other. A sentence about street food ends up far from both.
These are dense vectors: almost every position holds a non-zero value. They differ from the sparse vectors of keyword search, where each position stands for one word and most are zero. Dense vectors find matches that share no words, which keyword search cannot. They can also miss exact strings such as a product code, which is why retrieval systems often combine both.
An embedding comes from an embedding model, a neural network trained for this one job. It is not the chat model. In this course the embedding model is nomic-embed-text, served by the same local Ollama as the chat model. It is small (137 million parameters, against about 12 billion for the chat model), so embedding a batch of sentences is quick.
Query and document prefixes
Some embedding models are trained to treat the two sides of a search differently. The model card for nomic-embed-text v1.5 lists task prefixes: you start the text with search_document: when embedding something you will store, and with search_query: when embedding the question you will search with. Other prefixes exist for clustering and classification. Leaving the prefix out still gives a vector, but a different one, and the model was not trained to expect that.
Prefixes are a property of the model, not of vector search in general. Many other embedding models want no prefix, and some use their own wording. Read the model card of whichever model you adopt, and put the prefix handling in one function so that no caller can forget it. Our helper does that.
import numpy as np from llm import client, EMBED_MODEL def embed(texts, prefix="search_document: "): r = client.embeddings.create( model=EMBED_MODEL, input=[prefix + t for t in texts] ) return np.array([d.embedding for d in r.data])
embed.py: one batch call, with the document prefix by default.
The helper uses the OpenAI-compatible embeddings endpoint on the local server, the same client as llm.py, and returns a NumPy array with one row per input. Passing a list sends one request for the whole batch, which is cheaper than one request per sentence.
The model card's benchmark table lists a sequence length of 8,192 tokens, and the card says the model supports scaling past 2,048. The server on this machine reports a context length of 2,048 for this model (the /api/show output). Treat 2,048 as the limit here and check what your own server reports. The server does not state which release of the model it holds, so this chapter follows the v1.5 card and tests its claims, the prefixes in this lesson and the shorter sizes in lesson 6, on the model that is actually running.
Embedding three sentences
The script below embeds three sentences without any prefix and prints the shape and the first five values of the first vector. It then embeds the first sentence as a query and the other two as documents, with prefixes, and prints the two similarity scores. The last line prints the same two scores for the unprefixed vectors. The next lesson defines the score properly; for now, larger means closer.
import numpy as np from embed import embed sents = ["How do I reset my password?", "Steps to change a forgotten login password", "Best street food in Hyderabad"] v = embed(sents, prefix="") print(v.shape) print(np.round(v[0][:5], 4)) q = embed([sents[0]], prefix="search_query: ")[0] d = embed(sents[1:], prefix="search_document: ") print(np.round(d @ q, 3)) print(np.round(v[1:] @ v[0], 3))
(3, 768) [ 0.0057 0.0126 -0.1335 0.0226 0.0619] [0.693 0.312] [0.756 0.261]
Output from one run; yours will differ.
The shape is (3, 768): three sentences, 768 numbers each. The first values are small positive and negative numbers with no visible meaning. The paraphrase scores 0.693 against the query and the street-food sentence scores 0.312, so the ranking is right. The unprefixed scores are 0.756 and 0.261, the same order with different values.
That last point is the practical rule. Scores are only comparable when every vector in the comparison was made the same way. If you embed your documents with one prefix convention and your queries with another, the ranking can degrade without any error message. Decide the convention once, store it next to the index, and treat a change as a reason to re-embed everything.
How long is the vector for a one-word input compared with a 500-word input?
- The same: 768 numbers for this model. The length is set by the model, not by the text.
- Text past the model's input limit is cut off or rejected, so length is not a way to get more numbers.
Why does the helper add search_query: to queries and search_document: to stored text?
- The model was trained with those prefixes and expects them, so queries and documents are embedded the way the model learned to compare them.
Part 2 · Measuring similarity
Three ways to compare vectors
Once text is a vector, "how similar are these two texts" becomes "how close are these two vectors". Three measures cover almost everything you will meet. They look different, but for the vectors in this chapter they give the same ranking.
Dot product multiplies the vectors position by position and adds up the results. A larger value means the vectors point more the same way and, when they are long, it also grows with their length. Cosine similarity divides the dot product by the product of the two lengths, so it measures only the angle between the vectors. It runs from -1 (opposite) to 1 (same direction). Euclidean distance is the straight-line distance between the two points. Smaller means closer, which is the opposite direction from the other two.
| Measure | Formula | Better when | Looks at |
|---|---|---|---|
| Dot product | a · b | larger | angle and length |
| Cosine similarity | a · b / (|a| |b|) | larger | angle only |
| Euclidean distance | |a - b| | smaller | straight-line gap |
Formulaa · b
Better whenlarger
Looks atangle and length
Why the three agree on unit vectors
A vector with length 1 is a unit vector, and normalising means dividing a vector by its length to make it one. When both vectors are unit length, the two lengths in the cosine formula are 1, so cosine and dot product are the same number. Euclidean distance then follows from the dot product too. Expand the squared distance and you get |a - b|² = |a|² + |b|² - 2 a·b, which is 2 - 2 cos(a, b) for unit vectors. A larger cosine always means a smaller distance, so the rankings match.
Many embedding models return unit vectors, or are used with normalisation switched on, for exactly this reason. It lets a database use whichever operation is cheapest. The dot product is one multiply-and-add per dimension. It is the cheapest and the one that matrix hardware does best.
If the vectors are not unit length, the measures disagree. A long vector gets a large dot product with almost everything, so the dot product favours long vectors, while cosine ignores length. Some models are trained so that length carries information, and then a dot product is the intended measure. Again the model card decides.
The next script checks all of this on real vectors. It embeds one query and three documents, prints the length of each vector, then scores the documents with all three measures and prints the order each measure produces. The last row recomputes the Euclidean distance as the square root of 2 - 2 cos.
Running the three measures
import numpy as np from embed import embed docs = ["Steel flask keeps tea hot for twelve hours.", "Insulated bottle for hot drinks on a train.", "Soft cotton bedsheet with two pillow covers."] q = embed(["something to keep my chai warm while travelling"], prefix="search_query: ")[0] d = embed(docs) print("norms", np.round(np.linalg.norm(d, axis=1), 4), round(float(np.linalg.norm(q)), 4)) cos = d @ q / (np.linalg.norm(d, axis=1) * np.linalg.norm(q)) dot = d @ q euc = np.linalg.norm(d - q, axis=1) print("cosine ", np.round(cos, 3), np.argsort(-cos)) print("dot ", np.round(dot, 3), np.argsort(-dot)) print("euclid ", np.round(euc, 3), np.argsort(euc)) print("2-2cos ", np.round(np.sqrt(2 - 2 * cos), 3))
norms [1. 1. 1.] 1.0 cosine [0.572 0.625 0.515] [1 0 2] dot [0.572 0.625 0.515] [1 0 2] euclid [0.926 0.866 0.984] [1 0 2] 2-2cos [0.926 0.866 0.984]
Output from one run; yours will differ.
Every norm prints as 1.0, so the vectors from this server are unit length. Cosine and dot product are identical in every position. The last two rows match too: the distance computed directly (0.926, 0.866, 0.984) equals the square root of 2 - 2 cos. Document 1, the insulated bottle, is closest under all three measures, and the printed orders [1 0 2] are the same.
The scores are not far apart: the bedsheet scores 0.515 against 0.625 for the best match. Real embeddings are crowded. A score of 0.5 does not mean half related, and you cannot set one universal threshold such as 0.8 for "relevant". Compare scores within one query, and if you need a cut-off, choose it by looking at examples from your own data.
A model returns unit-length vectors. Which of dot product, cosine and Euclidean distance will rank results differently from the others?
- None of them. For unit vectors, cosine equals the dot product, and Euclidean distance is the square root of 2 - 2 cos, so the order is the same.
- Only the direction of 'better' differs: distance is smaller-is-closer.
Why do databases often store cosine as 1 - cosine similarity?
- So that every metric reads smallest-first, and one search routine, 'return the k smallest', works for all of them.
Part 3 · Exact search
Brute-force nearest neighbours
The simplest search is also the one that always finds the true answer. Exact nearest-neighbour search, also called brute force or a flat scan, compares the query with every stored vector and keeps the k best. For unit vectors that is one dot product per stored vector, which NumPy does for all of them in a single matrix-vector multiplication.
The cost is easy to state. With N stored vectors of d dimensions, one query costs N × d multiplications, written O(N·d). Doubling the catalogue doubles the time. Memory is N × d × 4 bytes for float32. Nothing else is needed: no index to build, no tuning, and the answer is exact.
Selecting the best k is the one detail worth knowing. Sorting all N scores costs more than necessary. np.argpartition moves the k largest scores to the front in linear time without fully sorting them, and then only those k are sorted. The function below does that.
def top_k(q, vecs, k=5): scores = vecs @ q k = min(k, len(scores)) idx = np.argpartition(-scores, k - 1)[:k] return idx[np.argsort(-scores[idx])], scores
The catalogue used here is 200 made-up product descriptions, one line each, such as "Small blue steel flask: keeps tea hot for twelve hours on a train journey." There are 25 kinds of product, each repeated eight times with a different colour and size, and the vectors are saved to a file once so every later script reuses them.
Three queries and a timing
The script embeds three queries with the query prefix, prints the top three matches for each, then times the search on the 200 real vectors and on 1,00,000 random vectors of the same width, to show how the cost grows.
import time import numpy as np from embed import embed from products import products texts = products(200) vecs = np.load("products.npy") queries = ["something to keep chai hot while travelling", "protect my phone from falls", "light for studying at night"] q = embed(queries, prefix="search_query: ")
for text, qv in zip(queries, q): idx, s = top_k(qv, vecs) print(text) for i in idx[:3]: print(f" {s[i]:.3f} {texts[i][:48]}") big = np.random.default_rng(0).standard_normal((100_000, 768)) big = big.astype("float32") t = time.perf_counter() top_k(big[0], big) print(f"100,000 vectors: {1000 * (time.perf_counter() - t):.1f} ms") t = time.perf_counter() top_k(q[0], vecs) print(f"200 vectors: {1000 * (time.perf_counter() - t):.3f} ms")
something to keep chai hot while travelling 0.686 Small blue steel flask: keeps tea hot for twelve 0.682 Large black steel flask: keeps tea hot for twelv 0.682 Small white steel flask: keeps tea hot for twelv protect my phone from falls 0.723 Medium yellow phone case: shock proof case that 0.723 Family size white phone case: shock proof case t 0.716 Medium black phone case: shock proof case that p light for studying at night 0.780 Medium blue desk lamp: adjustable lamp with warm 0.779 Medium green desk lamp: adjustable lamp with war 0.777 Medium white desk lamp: adjustable lamp with war 100,000 vectors: 7.2 ms 200 vectors: 0.253 ms
Output from one run. Timings are on this machine and vary from run to run.
Each query finds the right product kind. The flask query returns three flasks, the phone query three phone cases, the lamp query three desk lamps. Within a kind the scores differ in the third decimal place, because the descriptions differ only in colour and size. Do not read meaning into which colour comes first.
The timings show the scaling. Scanning 200 vectors took about a quarter of a millisecond, and scanning 1,00,000 took about 7 milliseconds in this run. That is 500 times as many vectors and about 30 times the time, because the small case is dominated by fixed overhead. Beyond that, time grows with N.
Where brute force stops being enough
Seven milliseconds is fine for a product search. Now count the memory and time at a larger size. 100 million vectors of 768 float32 values need 10,00,00,000 × 768 × 4 bytes, about 307 GB, more than a normal server holds. If scanning time kept growing in line with N, which is a rough estimate and not a measurement, it would be a thousand times the 1,00,000 case, several seconds per query. A search service that answers many users each second cannot afford that.
That gap is why approximate indexes exist, the subject of the next lesson. Before you reach for one, remember how much a flat scan handles: up to a few hundred thousand vectors, a flat scan on one machine is usually fast enough, and it never returns a wrong answer. Many production systems keep a flat index for small collections, and for the exact re-scoring step that follows an approximate search.
Watch for which products sit closest to the query on the map
Read it as steps
The query lands among the product vectors and the nearest five are ranked.
The scene shows a query on a two-dimensional map. The map is a projection of the 768-dimensional vectors down to two directions (principal components) for ten products, one of each of ten kinds, so distances on it only roughly match the real ones. The scores in the ranked list are the real cosine scores, not read off the map. The flask is clearly ahead at 0.686, and the next four products score between 0.557 and 0.543, which is the crowding the previous lesson warned about.
Part 4 · Approximate indexes
Trading a little recall for a lot of speed
An approximate nearest-neighbour (ANN) index returns neighbours that are very likely, but not guaranteed, to be the true ones, in return for far less work per query. Quality is measured by recall@k: the fraction of the true k nearest neighbours, as found by an exact scan, that the index also returned. A recall@10 of 0.95 means that on average 9.5 of the true top 10 came back.
Three families of index are common, and the FAISS library, an open-source similarity-search library from Meta, implements all of them. HNSW (Hierarchical Navigable Small World, Malkov and Yashunin, 2016) builds a graph. IVF (inverted file) partitions the space into cells. Product quantisation (PQ) compresses each vector into a short code. They answer different problems: HNSW and IVF reduce the number of vectors compared, PQ reduces the memory per vector, and IVF and PQ are often combined.
HNSW links each vector to a few near neighbours, in several layers. The top layer is sparse, with a few long links. Each lower layer holds more points and shorter links, and the bottom layer holds all of them. A search enters at the top, moves greedily to the neighbour closest to the query until no neighbour is closer, drops a layer, and repeats. Three settings matter. M is the number of links per point: more links give better recall and more memory. efConstruction is how widely the build explores, and efSearch is how widely each query explores. A larger efSearch costs time and raises recall.
Watch for the search stepping only to a neighbour that is closer to the query
Read it as steps
The greedy walk in code
This is the walk from the scene. Each point is linked to its two nearest points, and from the entry point the search repeatedly moves to its closest neighbour, stopping when none is closer than where it stands.
pts = {"A": (0.10, 0.50), "B": (0.28, 0.20), "C": (0.30, 0.80),
"D": (0.48, 0.50), "E": (0.55, 0.15), "F": (0.58, 0.85),
"G": (0.72, 0.45), "H": (0.88, 0.20), "I": (0.90, 0.75)}
query = np.array((0.80, 0.62))
P = {k: np.array(v) for k, v in pts.items()}
dist = lambda a, b: float(np.linalg.norm(a - b))
edges = set()
for a in P:
others = (n for n in P if n != a)
near = sorted(others, key=lambda n: dist(P[a], P[n]))
for b in near[:2]:
edges.add(tuple(sorted((a, b))))
def neighbours(a):
return [b if a == x else x for x, b in edges if a in (x, b)]node, steps = "A", [] steps.append(("visit", node, round(dist(P[node], query), 2))) while True: best = min(neighbours(node), key=lambda n: dist(P[n], query)) for n in sorted(neighbours(node)): steps.append(("look", n, round(dist(P[n], query), 2))) if dist(P[best], query) >= dist(P[node], query): break node = best steps.append(("visit", node, round(dist(P[node], query), 2))) for s in steps: print(*s) print("stopped at", node)
visit A 0.71 look B 0.67 look C 0.53 visit C 0.53 look A 0.71 look D 0.34 look F 0.32 visit F 0.32 look C 0.53 look I 0.16 visit I 0.16 look F 0.32 look G 0.19 stopped at I
Printed by the script. The walk is deterministic.
The search computed distances for seven of the nine points (E and H were never looked at) before stopping at I, 0.16 from the query. A full scan would have computed nine. With nine points the saving is small. With millions of points the walk still takes only a few dozen steps, because each hop gets closer and the long links in the upper layers let it cross the space quickly.
HNSW, IVF and PQ compared
The second script builds the three index types over 50,000 vectors of 768 dimensions and compares them with an exact flat index. The vectors are synthetic: random points drawn around 100 random centres and then normalised, so they have cluster structure like real embeddings but are not real text. Real data will give different numbers. The 200 query vectors are drawn the same way.
import time import faiss import numpy as np rng = np.random.default_rng(1) d, n, nq = 768, 50_000, 200 centres = rng.standard_normal((100, d)) def sample(m): pick = centres[rng.integers(0, 100, m)] x = pick + 1.5 * rng.standard_normal((m, d)) x /= np.linalg.norm(x, axis=1, keepdims=True) return x.astype("float32") xb, xq = sample(n), sample(nq) flat = faiss.IndexFlatIP(d) flat.add(xb) t = time.perf_counter() _, truth = flat.search(xq, 10) ms = 1000 * (time.perf_counter() - t) / nq print(f"flat recall 1.00 {ms:.2f} ms/query") def recall(ids): hits = [len(set(a) & set(b)) for a, b in zip(ids, truth)] return np.mean(hits) / 10 def timed(index): t = time.perf_counter() _, ids = index.search(xq, 10) return recall(ids), 1000 * (time.perf_counter() - t) / nq
hnsw = faiss.IndexHNSWFlat(d, 32, faiss.METRIC_INNER_PRODUCT) hnsw.hnsw.efConstruction = 100 t = time.perf_counter() hnsw.add(xb) print(f"hnsw build {time.perf_counter() - t:.1f} s") for ef in (8, 16, 64, 256): hnsw.hnsw.efSearch = ef r, ms = timed(hnsw) print(f"hnsw efSearch={ef:<3} recall {r:.2f} {ms:.2f} ms/query") quant = faiss.IndexFlatIP(d) ivf = faiss.IndexIVFFlat(quant, d, 224, faiss.METRIC_INNER_PRODUCT) ivf.train(xb) ivf.add(xb) for p in (1, 4, 16, 64): ivf.nprobe = p r, ms = timed(ivf) print(f"ivf nprobe={p:<3} recall {r:.2f} {ms:.2f} ms/query") pq = faiss.IndexPQ(d, 96, 8, faiss.METRIC_INNER_PRODUCT) pq.train(xb) pq.add(xb) r, ms = timed(pq) print(f"pq 96x8 recall {r:.2f} {ms:.2f} ms/query") print("bytes per vector: float32", 4 * d, "pq", pq.code_size)
flat recall 1.00 1.62 ms/query hnsw build 3.2 s hnsw efSearch=8 recall 0.68 0.04 ms/query hnsw efSearch=16 recall 0.84 0.04 ms/query hnsw efSearch=64 recall 0.99 0.06 ms/query hnsw efSearch=256 recall 1.00 0.12 ms/query ivf nprobe=1 recall 0.71 0.03 ms/query ivf nprobe=4 recall 1.00 0.05 ms/query ivf nprobe=16 recall 1.00 0.18 ms/query ivf nprobe=64 recall 1.00 0.67 ms/query pq 96x8 recall 0.38 0.35 ms/query bytes per vector: float32 3072 pq 96
Output from one run. Build and query times are on this machine and vary.
Reading the comparison
The flat index is exact by definition. HNSW with efSearch=8 found 0.68 of the true top 10, with efSearch=64 it found 0.99, and by 256 it found all of them, at a time per query that stayed well below the flat scan. The IVF index with 224 cells found 0.71 when it visited one cell (nprobe=1) and everything once it visited four. Past that, visiting more cells only costs time.
The last index is IndexPQ with 96 sub-vectors of 8 bits each. Each 3,072-byte vector became a 96-byte code, 32 times smaller, and recall fell to 0.38, because the vectors are now approximations. In practice PQ codes are used to find candidates quickly and a second step re-scores a short list with the original vectors, which restores most of the accuracy.
Recall rises with efSearch or nprobe and so does time. You pick the cheapest setting that meets your recall target on your own data. The settings that gave 0.99 on this synthetic set may not on yours.
What does recall@10 = 0.9 mean for an ANN index?
- On average 9 of the true 10 nearest neighbours, as found by an exact scan, are among the 10 results.
- It says nothing about the order of those results.
Why does PQ cut memory but lower recall?
- Each part of a vector is replaced by the index of its nearest centroid, a short code. The stored vector is only an approximation, so some distances rank wrongly.
Predict: you need recall@10 of at least 0.95, and HNSW at efSearch=16 gave 0.84 in the run above. What do you change first, and what do you measure afterwards?
- Raise
efSearch, for example to 64, which gave 0.99 here, and then measure recall and time per query again on your own data. - Recall rises with
efSearchand so does latency, so you keep the smallest value that meets the target. RaisingMis a build-time change that costs memory.
Part 5 · What a vector database adds
From an index to a database
An index answers one question: which stored vectors are closest to this one. A real application needs more. It must keep the vectors after a restart, update or delete a product when the catalogue changes, restrict a search to rows that meet a condition, and keep each customer's data apart from others. A vector database is a store that adds these things around one or more indexes.
Persistence means the data lives on disk and survives a crash, with the vector stored beside the original text and its identifier. Updates and deletes matter because many ANN structures are built in one go and can be awkward to change afterwards, so databases handle edits in different ways, and you should read how yours does. Metadata filters restrict candidates by ordinary columns, such as price below 400 or tenant equal to 42. Hybrid search combines vector scores with keyword scores, which RAG systems use. Tenancy means separating one customer's vectors from another's, which is a security matter and not only a convenience.
The vector might live in a dedicated engine or an extension of a database you already run. Extensions, such as sqlite-vec for SQLite and pgvector for PostgreSQL, let you keep vectors next to your other data and use ordinary SQL. A dedicated engine usually offers more index choices and scaling features. For a first project, or a collection of a few hundred thousand vectors, the extension you already have is often enough.
Filtering, and a trap
Filtering interacts with approximate search in a way that surprises people. If an index finds its 10 nearest candidates first and the filter is applied afterwards, a selective filter can throw away most of them, and you get fewer than 10 rows back, or none. The pgvector documentation says this about its approximate indexes: the filter is applied after the index scan, so a selective condition can return fewer rows than asked for. It offers iterative index scans, enabled with a setting such as SET hnsw.iterative_scan = strict_order;, which keep scanning until enough rows pass.
Exact scans do not have this problem, because every row is checked. sqlite-vec began as a brute-force engine: its author's release announcement says it is focused on fast brute-force search and that approximate indexes would come later, and the documentation pages on tables and queries do not mention one. Check the release notes of the version you install before you assume either way. At the sizes in this course it makes no difference, and the filter in its query is simply part of the same scan. If you need to filter by tenant on a larger set, a partition key, which splits the vectors into separate shards, avoids scanning the rest.
pgvector's operators are <-> for Euclidean distance, <#> for negative inner product, <=> for cosine distance and <+> for L1 distance. Its HNSW index is created with an operator class that names the measure, with m defaulting to 16, ef_construction to 64, and a query-time hnsw.ef_search of 40. IVFFlat's ivfflat.probes defaults to 1. These defaults are from the project's README. The block below is the shape of a filtered query in pgvector. It is shown and not run, because there is no PostgreSQL on this machine.
create extension vector; create table items ( id bigserial primary key, price integer, embedding vector(768)); create index on items using hnsw (embedding vector_cosine_ops) with (m = 16, ef_construction = 64); set hnsw.ef_search = 40; select id from items where price < 400 order by embedding <=> '[...]' limit 5;
Shape only, not run: checked against the pgvector README.
A vector table in SQLite
The script below loads the 200 product vectors into a vec0 virtual table from the sqlite-vec package, version 0.1.9. The table has an integer key, a 768-wide float vector that uses cosine distance, and a price metadata column that the query can filter on. A KNN query uses match, a k constraint and any filter, and returns a distance column.
import sqlite3 import numpy as np import sqlite_vec from embed import embed from products import products texts = products(200) vecs = np.load("products.npy") db = sqlite3.connect(":memory:") db.enable_load_extension(True) sqlite_vec.load(db) db.execute("""create virtual table items using vec0( id integer primary key, embedding float[768] distance_metric=cosine, price integer)""")
for i, v in enumerate(vecs): db.execute("insert into items values (?, ?, ?)", (i, v.tobytes(), 199 + 50 * (i % 10))) q = embed(["protect my phone from falls"], prefix="search_query: ")[0] sql = """select id, distance, price from items where embedding match ? and k = 3 {} order by distance""" for extra in ("", "and price < 400"): print("filter:", extra or "none") args = (q.astype("float32").tobytes(),) for id_, dist, price in db.execute(sql.format(extra), args): print(" ", id_, round(dist, 3), price, texts[id_][:34]) print(db.execute("select vec_version()").fetchone()[0])
filter: none 140 0.277 199 Medium yellow phone case: shock pr 115 0.277 449 Family size white phone case: shoc 90 0.284 199 Medium black phone case: shock pro filter: and price < 400 140 0.277 199 Medium yellow phone case: shock pr 90 0.284 199 Medium black phone case: shock pro 40 0.284 199 Medium red phone case: shock proof v0.1.9
Output from one run; yours will differ.
The first query has no filter. Its top three are phone cases, two of them cheap (199) and one costing 449. With the filter price < 400, the 449 item drops out and the next closest cheap case takes its place, so the results are still three rows. The distances are cosine distances: 0.277 here is 1 - 0.723, the cosine similarity the flat scan gave in lesson 3.
Notice what the database did that the NumPy script did not: the vectors sit in a table you could keep in a file, they are tied to an identifier and a price, and the filter was expressed as part of the query. For a larger catalogue you would add tenant or category columns the same way.
Part 6 · Choosing and sizing
Counting memory first
Sizing a vector store begins with arithmetic. Raw memory for the vectors is the number of vectors times the dimensions times the bytes per number. For 10 million vectors of 768 float32 values, that is 1,00,00,000 × 768 × 4 bytes, about 30.7 GB. An HNSW graph adds its links on top, and the original text and metadata are extra again.
Memory saved: 32 times (3,072 bytes down to 96, at some recall cost)
Read it as steps
Full float32 vectors against product-quantised codes.
The scene repeats the arithmetic and shows the PQ alternative from lesson 4: 96-byte codes for the same ten million vectors need about 0.96 GB, 32 times less, at the recall cost seen earlier. Two other levers exist. Store fewer dimensions, which the next page measures, or store numbers in fewer bits, such as 8-bit integers, which many databases offer. Each trades accuracy for memory, and the only way to know the cost for your data is to measure recall on your own queries.
Memory also decides where the index can live. A collection that fits in RAM can be searched in milliseconds. One that does not must go to disk, with slower queries, or be spread over several machines, with the operations work that brings. This is why dimension and precision, which look like minor settings, are first-order design choices.
Shorter vectors: Matryoshka truncation
Some embedding models are trained with Matryoshka representation learning, named after nesting dolls, so that the first part of the vector is already a usable, smaller embedding. The model card for nomic-embed-text v1.5 lists the sizes 768, 512, 256, 128 and 64. You keep the first n numbers and normalise again to unit length. The card describes a layer normalisation before cutting as the recommended routine. The experiment below keeps it simpler and only slices and re-normalises, which is enough to show the effect on this model.
To measure the cost, take 15 made-up queries, run an exact search over the 200 product vectors at 768 dimensions, and treat those top five results as the reference. Then search again with the vectors cut to each smaller size and count how many of the reference five come back. That is recall@5 against the full-size result.
import numpy as np from embed import embed vecs = np.load("products.npy") queries = [ "something to keep chai hot while travelling", "protect my phone", "light for studying at night", "bag for my tablet in the rain", "cook dal fast", "stretching mat for exercise", "keep mosquitoes away", "carry lunch to office without leaks", "cool a small room cheaply", "tea cup that does not rust", "safe lock for my cycle", "make filter coffee at home", "oil for dry hair", "stationery for school", "umbrella for monsoon"] q = embed(queries, prefix="search_query: ") def top5(dim): d, qq = vecs[:, :dim], q[:, :dim] d = d / np.linalg.norm(d, axis=1, keepdims=True) qq = qq / np.linalg.norm(qq, axis=1, keepdims=True) return np.argsort(-(qq @ d.T), axis=1)[:, :5] full = top5(768) for dim in (512, 256, 128, 64): t = top5(dim) r = np.mean([len(set(a) & set(b)) / 5 for a, b in zip(t, full)]) print(f"{dim:>3} dims recall@5 vs 768: {r:.2f} " f"bytes/vector {4 * dim}")
512 dims recall@5 vs 768: 0.89 bytes/vector 2048 256 dims recall@5 vs 768: 0.89 bytes/vector 1024 128 dims recall@5 vs 768: 0.77 bytes/vector 512 64 dims recall@5 vs 768: 0.71 bytes/vector 256
Output from one run; yours will differ.
Cutting to 256 dimensions kept 0.89 of the reference top five and shrank each vector from 3,072 bytes to 1,024, three times smaller. At 64 dimensions recall fell to 0.71. Treat these numbers as rough. The catalogue holds eight near-identical variants of each product, so which five of those variants rank first is close to arbitrary and any change pushes some out, which makes the recall look lower than it would on a more varied collection. The shape of the result, a plateau from 768 down to 256 and then a fall, is what to expect, but measure on your own data.
Choosing an embedding model
The choice of embedding model is a choice you will live with, because changing it means re-embedding everything. Vectors from two different models, or from the same model with different prefixes or sizes, cannot be compared. Store the model name, version, prefix convention and dimension next to the index, so you can tell what an index holds and re-embed on purpose.
| Question | Why it matters |
|---|---|
| Quality on your task | Test candidate models on your own queries with a labelled set; public rankings do not cover your data. |
| Languages | A model trained mostly on English may do poorly on Hindi or Telugu text. |
| Input length | Longer inputs let you embed bigger chunks. Check the limit your server actually enforces. |
| Dimensions and size | Memory per vector, and the speed of the embedding call itself. |
| Licence and hosting | nomic-embed-text is released under Apache-2.0 and runs locally, so no text leaves the machine. |
| Prefixes and normalisation | Needed to use the model correctly; put them in one function. |
There is no single best model. A sound process is to pick two or three candidates that fit your languages and limits, embed a few hundred real documents and 50 real queries with known answers, and compare recall@k, query speed and memory. Build that labelled set by hand, and compute recall@k on it.
Finally, remember what the vector store is not. It finds text that is close in meaning, not text that is correct or permitted. Whether a result may be shown to this user, or answers the question, is decided by your own checks, such as a permission filter on the metadata, and not by the vector store.