pgvector with Django, part 4: distances and indexes, staying fast with millions of documents
With six documents the database compares everything in an instant, with six million it does not. How does pgvector stay fast as documents grow, and what is the price? Let's talk about distances and indexes.
First question: what does "close" mean?
So far we have used a single kind of distance, "cosine". pgvector has three, each with its own SQL operator and its own Django class:
| Distance | SQL operator | Django class | How to picture it |
|---|---|---|---|
| Cosine | <=> | CosineDistance | The angle between two arrows: it looks at direction, not length |
| Euclidean (L2) | <-> | L2Distance | The straight-line distance between two points on the map |
| Inner product | <#> | MaxInnerProduct | How much two arrows point the same way, multiplied by their length |
To see the difference, try this directly in the database, with two points of three numbers:
SELECT '[1,2,3]'::vector <-> '[4,5,6]'::vector AS l2,
'[1,2,3]'::vector <=> '[4,5,6]'::vector AS cosine,
'[1,2,3]'::vector <#> '[4,5,6]'::vector AS inner_product;
The result is about 5.196 for the Euclidean distance, 0.025 for cosine and −32 for the inner product. Note that minus sign: the <#> operator returns the product with its sign flipped, because PostgreSQL sorts from smallest to largest and here "larger" means "more similar".
Which one to pick? For text, almost always cosine: embedding models are designed for it, and it gives values that are easy to read. The golden rule is another one: use the same distance the model expects. And then the index (we get to it shortly) has to be built for that distance, or it will not be used.
The problem: searching among millions of points
So far, for every search the database computed the distance between your point and all the others, then sorted them. This is called exact search: it always finds the true nearest ones, but the time grows with the number of documents. With six documents nobody notices; with millions, every search becomes slow.
The solution is the same as for books in a library: instead of looking at every book, you look at the right shelves. For vectors this is an index, and it has a price: instead of the exact answer, it gives an approximate one. Almost always it finds the true neighbours, but now and then it misses one. It is a trade-off between speed and precision, and it lets you choose where to stand.
pgvector offers two kinds of index.
HNSW: the multi-level map
HNSW works like a road network with several levels. At the top are the motorways, few and fast, that take you straight to the right area; further down the main roads, then the neighbourhood streets. You start at the top, get close in big steps, and descend until you find the true neighbours.
In Django you declare it inside the model:
from pgvector.django import HnswIndex, VectorField
class Documento(models.Model):
titolo = models.CharField(max_length=200)
testo = models.TextField()
embedding = VectorField(dimensions=1024, null=True, blank=True)
class Meta:
indexes = [
HnswIndex(
name="documento_embedding_hnsw",
fields=["embedding"],
m=16,
ef_construction=64,
opclasses=["vector_cosine_ops"],
)
]
Then, as always, makemigrations and migrate. The parameters:
m: how many links each point has to its neighbours. Higher means more precise and heavier. 16 is the default.ef_construction: how carefully the index is built. Higher gives a better index and slower creation. Default: 64.opclasses: says which distance the index is built for.vector_cosine_opsis for cosine; for the other two there arevector_l2_opsandvector_ip_ops.
At search time there is a third parameter you can change on the fly, hnsw.ef_search: how many candidates the search explores. The default is 40; raising it makes the search more precise and a little slower:
from django.db import connection, transaction
with transaction.atomic():
with connection.cursor() as cursor:
cursor.execute("SET LOCAL hnsw.ef_search = 100")
# ... your search goes here ...
With SET LOCAL the value applies only inside that transaction, then goes back to 40.
IVFFlat: splitting into groups
IVFFlat does something simpler: first it divides all the points into a certain number of groups (lists), then, at each search, it looks only at the groups closest to your point.
from pgvector.django import IvfflatIndex
IvfflatIndex(
name="documento_embedding_ivf",
fields=["embedding"],
lists=100,
opclasses=["vector_cosine_ops"],
)
The lists parameter is the number of groups, and at search time ivfflat.probes matters: how many groups to examine (default: 1). With 1 you are fast, but you may miss a result sitting in a nearby group; raising it gains precision and loses speed.
One important particularity: IVFFlat builds its groups by looking at the data that exists at the moment of creation. If you create it on an empty table, the groups make no sense. It must be created after loading a good number of documents.
Which one to choose
- HNSW is, as a rule, the safest choice: a good balance of speed and precision, and it can be created on an empty table. It uses more memory and costs more to build.
- IVFFlat builds faster and weighs less, but needs data to be there already and is usually a little less precise at the same speed.
For an archive that grows over time, I would start with HNSW.
How to know the index is really working
An index that is not used is wasted time. Django has explain():
from pgvector.django import CosineDistance
q = [0.1] * 1024 # any vector, just for the test
print(Documento.objects.annotate(d=CosineDistance("embedding", q)).order_by("d")[:3].explain())
In the answer, look for this line:
Index Scan using documento_embedding_hnsw on archivio_documento
If it is there, the index is working. If you see Seq Scan, the database is looking at everything. Three rules for it to be used: the query must have an order_by on the distance, a LIMIT (that is, the square brackets [:3]), and the distance must be the same as the index's.
A warning about filters
If you add a filter to the search, for example "only this customer's documents", an approximate index can return fewer results than you asked for: it first finds the close candidates, and only then filters them. This is a known behaviour, and recent versions of pgvector have tools to soften it. Before going to production, try a search with a very restrictive filter on your version and check how many results you get.
Next part
In the last part we bring the two worlds together: search by words and search by meaning, in a single search. Because sometimes "fattura 114" is better found with words, and sometimes "come disdire l'affitto" only with meaning.