pgvector with Django, part 3: from documents to vectors (and why the model matters)
Who computes the coordinates of your documents? An AI model, and the choice changes everything: I tried the same example with three different models, and one gets it wrong.
Who turns text into numbers
In part 2 we made the coordinates up. With a real document you cannot: you need an embedding model, an artificial intelligence program that reads a text and returns its vector.
There are two families:
- Models you run yourself, on your computer or your server. They are free and your documents never leave your machine, but you have to download them and let them work.
- External services, paid, that return the vector over the internet. Convenient and often very good, but your texts travel to another provider, and if the service changes or stops you depend on it.
In this series I use a local model. To try it I use a lightweight library, fastembed, which downloads models and runs them without needing a graphics card.
The experiment: same example, three models
I prepared six short Italian documents (a lease, an invoice, minutes of a shareholders' meeting, a car insurance policy, a boiler manual, a building's house rules) and asked the question from part 1: "come disdire l'affitto" ("how to cancel the rent"). The lease contains neither "disdire" nor "affitto": it only says the tenant may exercise the right of withdrawal.
I used Italian on purpose: three multilingual models that can read it, and a harder test than English.
Here is where the lease ends up with each model:
| Model | Dimensions | The lease for "come disdire l'affitto" |
|---|---|---|
| paraphrase-multilingual-MiniLM-L12-v2 | 384 | Not even in the top three |
| paraphrase-multilingual-mpnet-base-v2 | 768 | Second place |
| multilingual-e5-large | 1024 | First place (distance 0.152) |
The small model, the fastest and lightest (about 0.2 GB), does not get there. The large one, about 2.2 GB to download, gets there and puts it first. This is the most important lesson of this part: a search-by-meaning system is only as good as its model. The database, pgvector, does its job identically every time; but if the vectors are mediocre, so are the results.
For the rest of the series I use multilingual-e5-large, which at 1024 dimensions is the most capable of the three.
The code: computing the vectors
Add the library to the project:
uv add fastembed
And create a file archivio/embedding.py:
from fastembed import TextEmbedding
modello = TextEmbedding("intfloat/multilingual-e5-large")
def vettori_documenti(testi):
return list(modello.embed(["passage: " + t for t in testi]))
def vettore_domanda(testo):
return list(modello.embed(["query: " + testo]))[0]
Two things to know:
- The first time you run it, the model is downloaded (about 2.2 GB). After that it is already on disk.
- The prefixes
passage:andquery:are not a whim: the model's authors prescribe them, because it was trained that way, and without them results get worse. Every model has its own instructions: always read the page of the one you choose.
The Django model with 1024 dimensions
In archivio/models.py add:
from pgvector.django import VectorField
class Documento(models.Model):
titolo = models.CharField(max_length=200)
testo = models.TextField()
embedding = VectorField(dimensions=1024, null=True, blank=True)
def __str__(self):
return self.titolo
The number 1024 must match the model's dimensions: if it does not, the database refuses the vector. Then:
uv run python manage.py makemigrations archivio -n documento
uv run python manage.py migrate
Loading documents and searching
From the shell (uv run python manage.py shell):
from archivio.models import Documento
from archivio.embedding import vettori_documenti, vettore_domanda
from pgvector.django import CosineDistance
DOCS = [
("Contratto di locazione", "Il conduttore può esercitare il diritto di recesso con preavviso di sei mesi."),
("Fattura 2026/114", "Fattura n. 114 del 3 marzo 2026 per la fornitura di materiale d'ufficio."),
("Verbale assemblea", "L'assemblea dei soci approva il bilancio e nomina il nuovo consiglio di amministrazione."),
("Polizza auto", "La polizza copre i danni al veicolo in caso di incidente stradale o furto."),
("Manuale caldaia", "Per spegnere la caldaia ruotare la manopola sulla posizione zero e chiudere il gas."),
("Regolamento condominiale", "È vietato lasciare biciclette e oggetti ingombranti nelle scale e nei corridoi comuni."),
]
vettori = vettori_documenti([f"{titolo}. {testo}" for titolo, testo in DOCS])
Documento.objects.bulk_create([
Documento(titolo=t, testo=x, embedding=v)
for (t, x), v in zip(DOCS, vettori)
])
q = vettore_domanda("come disdire l'affitto")
for d in Documento.objects.annotate(distanza=CosineDistance("embedding", q)).order_by("distanza")[:3]:
print(f"{d.distanza:.3f} {d.titolo}")
The result:
0.152 Contratto di locazione
0.196 Manuale caldaia
0.203 Regolamento condominiale
The lease comes first, without the question containing a single word from the text.
I tried three more questions, with the same model:
| Question | First result | Distance |
|---|---|---|
| pagare una fattura (pay an invoice) | Fattura 2026/114 | 0.160 |
| cosa fare se mi rubano la macchina (what to do if my car is stolen) | Polizza auto (car insurance policy) | 0.149 |
| parcheggiare la bici nell'androne (park the bike in the entrance hall) | Regolamento condominiale (house rules) | 0.180 |
An observation that will save you trouble
Look at the numbers: they all sit between 0.15 and 0.25, even between the right document and the wrong one. With this model distances bunch up in a narrow band, and the runner-up is often close to the winner.
Practical consequence: you cannot copy a "threshold" from another project, for example "discard anything beyond 0.5". Every model has its own scale, and the right threshold is found by trying it on your own documents.
Four things to remember before using it for real
- Changing model means recomputing everything. Vectors from two models cannot be compared. It is wise to store the name of the model next to each document.
- Long texts must be split. Every model reads only a limited amount of text at a time (this one, about 512 "word pieces"). A long document is divided into passages, and each passage gets its own vector.
- The computation is slow compared with an ordinary search. You do it once, when the document comes in, and usually in a background process, not while the user waits.
- Measure with real questions. Prepare twenty questions your users would really ask and check, every time you change the model, that the right document stays near the top.
Next part
With six documents the database compares everything in an instant. With six million, it does not. In part 4 we talk about distances and indexes: how pgvector stays fast when the documents become many, and what price you pay.