Sub topic 1
What Embeddings Are and Why Similarity Search Needs a Database
Prerequisites
This chapter assumes you can read basic SQL (CREATE TABLE, INSERT, SELECT, WHERE, ORDER BY, LIMIT) and have used PostgreSQL through psql or another client. You should have a rough idea of what a text or image embedding is. The Python snippets use NumPy and are optional. No pgvector installation is needed yet, because the extension is enabled in a later chapter.
What an embedding is
An embedding is a list of floating-point numbers that represents a piece of data, such as a sentence, a product photo, or a support ticket. A trained model produces the list. The model is trained so that items with similar meaning get lists that are close together, and items with unrelated meaning get lists that are far apart.
The list is called a vector, and its length is the number of dimensions. Common models produce vectors with 384, 768, 1024, or 1536 dimensions. A single dimension usually has no human-readable meaning. Only the position of the whole vector relative to other vectors carries information.
This lets you search by meaning instead of by exact words. A keyword search for "cheap flights" will not match a document titled "low-cost airfare." The two phrases get nearby embeddings, so a nearest-neighbor search finds the document anyway.
From data to a ranked answer
Similarity search follows the same steps in almost every application:
- Run each item through an embedding model and store the resulting vector.
- At query time, run the user's query through the same model.
- Find the stored vectors nearest to the query vector.
- Return the items those vectors belong to, ranked by distance.
Step 3 is the work of this tutorial. Steps 1 and 2 happen outside the database, in your application or a service you call.
Closeness is a distance
"Close" needs a definition. A distance function takes two vectors and returns one number. A smaller number means the vectors are more alike. The three you will meet most often are Euclidean distance (L2), cosine distance, and negative inner product. The next chapter compares them and explains how to choose one. For now, the useful point is that every one of them reduces a comparison of two vectors to a single number you can sort by.
A nearest-neighbor query is therefore a sort. You compute the distance from the query vector to each stored vector, order the results from smallest to largest, and keep the first k. That is the same shape as ORDER BY ... LIMIT k, which is why SQL is a natural place for it.
A toy example
The following script uses three dimensions so you can check the numbers by hand. Real embeddings behave the same way with hundreds of dimensions.
import numpy as np
items = {
"a": np.array([1.0, 2.0, 3.0]),
"b": np.array([4.0, 5.0, 6.0]),
"c": np.array([1.0, 1.0, 1.0]),
}
query = np.array([3.0, 1.0, 2.0])
distances = {name: float(np.linalg.norm(vec - query)) for name, vec in items.items()}
for name, dist in sorted(distances.items(), key=lambda pair: pair[1]):
print(name, round(dist, 3))The output is:
c 2.236
a 2.449
b 5.196Item c is nearest to the query, then a, then b. Later chapters run the same ranking in SQL with the same three rows.
Why brute force stops working
The script above compares the query against every item. This is exact, which is good, but its cost grows linearly with the number of rows and with the number of dimensions. The next script tries it on 100,000 random vectors with 384 dimensions.
import time
import numpy as np
rng = np.random.default_rng(0)
data = rng.standard_normal((100_000, 384), dtype=np.float32)
query = rng.standard_normal(384, dtype=np.float32)
start = time.perf_counter()
distances = np.linalg.norm(data - query, axis=1)
top5 = np.argsort(distances)[:5]
elapsed = time.perf_counter() - start
print(top5.tolist())
print(f"{elapsed * 1000:.1f} ms")The timing depends on your machine, but a full pass over 100,000 vectors usually takes tens of milliseconds. Memory is a larger problem. Each float32 takes 4 bytes, so this array is about 154 MB. One million vectors of 1536 dimensions need roughly 6 GB, and every query reads all of it.
Memory use and query time grow with the table, so a script that holds everything in RAM works for a demo and fails in production.
What a database adds
Keeping vectors in a NumPy array or a flat file leaves several problems for you to solve. A database handles them.
- Persistence. Vectors survive restarts and are not rebuilt from the source data every time.
- Updates. Rows can be inserted, changed, and deleted while other clients read them, with transactions keeping the data consistent.
- Indexes. A database can build a structure that answers nearest-neighbor queries without reading every row. Later chapters cover the two pgvector offers, HNSW and IVFFlat.
- Filtering. Real searches have conditions, such as "only documents this user may see" or "only products in stock." A database combines those conditions with the vector ordering in one query.
- Access control. Roles and permissions apply to vectors as they apply to any other column.
Why pgvector and PostgreSQL
pgvector is an extension that adds a vector column type, distance operators, and approximate indexes to PostgreSQL. The main benefit is that embeddings live next to the data they describe. A row can hold the text, the metadata, and the embedding, and one query can join, filter, and rank.
This has trade-offs. A dedicated vector database may offer features or scale that a single PostgreSQL server does not. In exchange, you avoid a second system, a second copy of your data, and the job of keeping the two in sync. For many applications, up to millions of vectors, the PostgreSQL approach is enough. Measure with your own data before deciding.
Common mistakes
- Mixing models. Vectors from different embedding models are not comparable, even when they have the same dimension. Store and query with the same model and, ideally, the same version. If you change models, re-embed everything.
- Treating similarity as a guarantee. A nearest neighbor is only the closest stored item. It may still be a poor match. Rank order is reliable, but the distance value alone does not tell you the result is relevant.
- Ignoring dimension. A table column has a fixed number of dimensions. The model you choose decides that number, so pick the model before you create the table.
- Assuming an index is exact. Indexes make queries faster by sometimes returning slightly wrong neighbors. Without an index, results are exact. This trade-off is covered in detail later.
Exercise
A table holds 2 million embeddings with 768 dimensions stored as 4-byte floats. About how much raw vector data does a brute-force search read per query, ignoring row overhead?
Show answer
2,000,000 rows x 768 dimensions x 4 bytes = 6,144,000,000 bytes, or about 6.1 GB. Every query that has no index must read all of it, which is why indexes matter at this size.
Exercise
You embed documents with model X, then later embed user queries with model Y, which has the same number of dimensions. Will nearest-neighbor results be meaningful? Why or why not?
Show answer
No. Each model places meaning in its own coordinate space, so distances between vectors from different models do not reflect similarity. The matching dimension count only prevents an error. It does not make the comparison valid. Re-embed the documents with the same model used for queries.
Exercise
Give two reasons to store embeddings in PostgreSQL instead of a NumPy array on disk.
Show answer
Any two of the following: vectors persist and can be updated transactionally, indexes avoid scanning every row, a WHERE clause can filter by metadata in the same query, and existing roles and permissions apply. Keeping vectors beside the source rows also avoids synchronizing a second system.