pgvector with Django, part 5: hybrid search, words and meaning together
Sometimes "invoice 114" is better found with words, and "how to cancel the rent" only with meaning. The last part joins them in a single search, and gathers the lessons to take home.
Why one of the two is not enough
Let's compare the two ways of searching on the same six documents from part 3 (the examples are in Italian, as before).
Search by words (PostgreSQL full-text search, with the rules of the Italian language):
- "recesso" (withdrawal) finds the lease.
- "biciclette" (bicycles) finds the house rules.
- "disdire affitto" (cancel rent) finds nothing: those words are not in the lease.
Search by meaning (pgvector): "come disdire l'affitto" brings the lease to first place. But it is weaker with exact things: an invoice number, a code, a surname are pieces of text that meaning "blurs".
The two searches go wrong in different places. So, used together, they correct each other.
The idea: let the two rankings vote
How do you mix two rankings if their scores are not comparable? One gives distances like 0.152, the other relevance "ranks" on a different scale.
A simple and effective trick is called Reciprocal Rank Fusion. It does not look at scores, only at position in the ranking. Each document gets 1 / (60 + position) from every ranking it appears in, and the points are added up. First place is worth about 0.0164, second a little less, and so on. A document that appears in both lists gets double and flies to the top.
The number 60 is a traditional value that smooths the differences among the top positions: it rarely needs changing.
The code
Add this in archivio/ricerca.py:
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
from pgvector.django import CosineDistance
from archivio.embedding import vettore_domanda
from archivio.models import Documento
def ricerca_ibrida(domanda, quanti=3, k=60):
# 1) by meaning
vettore = vettore_domanda(domanda)
per_significato = list(
Documento.objects.annotate(d=CosineDistance("embedding", vettore))
.order_by("d")
.values_list("id", flat=True)[:20]
)
# 2) by words
testo = SearchVector("titolo", "testo", config="italian")
ricerca = SearchQuery(domanda, config="italian", search_type="websearch")
per_parole = list(
Documento.objects.annotate(v=testo)
.filter(v=ricerca)
.annotate(rango=SearchRank(testo, ricerca))
.order_by("-rango")
.values_list("id", flat=True)[:20]
)
# 3) add up the votes
punti = {}
for lista in (per_significato, per_parole):
for posizione, pk in enumerate(lista, start=1):
punti[pk] = punti.get(pk, 0) + 1 / (k + posizione)
migliori = sorted(punti, key=punti.get, reverse=True)[:quanti]
documenti = Documento.objects.in_bulk(migliori)
return [(documenti[pk].titolo, round(punti[pk], 4)) for pk in migliori]
The three parts are visible in the code: search by meaning, search by words (with config="italian", which knows that "affitti" and "affitto" are relatives; for English documents use config="english"), and the sum of the votes.
What happens, with real numbers
I tried three questions, with the same archive of six documents:
| Question | First result | Points | Why |
|---|---|---|---|
| come disdire l'affitto (how to cancel the rent) | Contratto di locazione (lease) | 0.0164 | Only meaning finds it: the words give nothing |
| fattura 114 (invoice 114) | Fattura 2026/114 | 0.0328 | First in both lists: double points |
| biciclette nel corridoio (bicycles in the corridor) | Regolamento condominiale (house rules) | 0.0164 | First by meaning |
The invoice case is the instructive one: the score, 0.0328, is exactly double the others, because the number "114" is a clue that words find at once and that meaning confirms. The runner-up is far behind, at 0.0161.
Lessons to take home
After five parts, here is what I feel I can tell you, in order of importance:
- The model matters more than the database. pgvector does its job well and the same for everyone; quality is decided by the embedding model. Try more than one, with your own texts, before choosing.
- Store the model's name next to the vectors. The day you change it, you know what has to be recomputed.
- Split long texts into passages. One vector for a whole book says little. One vector per passage, with a reference to the source document, says a lot.
- Apply permissions inside the query. In an archive with several users, the "only documents you can see" filter belongs in the same search, not after it: otherwise you risk showing, or dropping, the wrong thing.
- Never show distances to the user. They are useful to you, not to them. Show the order of the results.
- Prepare twenty real questions and check, at every change, that the right document stays near the top. It is the only way to notice a regression.
- Do not throw away search by words. It stays the best for codes, numbers and proper names. Hybrid search exists for that.
Where I used it
In DjangoVault, the document management system I build in my book, search by words and search by meaning live side by side, and even the Ctrl+K shortcut searches by meaning. On top of these there is an assistant that answers questions by citing the passages of the documents its answer comes from. If you want to see how it is built, chapter by chapter, here is the book: Building a Document Management System.
The series
- Part 1: how to teach a database to understand meaning
- Part 2: your first vector in 15 minutes
- Part 3: from documents to vectors
- Part 4: distances and indexes
Thank you for following the series. If you have a question or a case you would like to see explained, write to me at info@frankybonanno.it: it could become a new part.