Searching case law by meaning: what vector search solves and what it does not
You look for precedents on a defect of consent, and the right judgment talks about "essential mistake" (errore essenziale) and "voidability" (annullabilità): none of your words appears in the text. Keyword search does not find it, and it is not an oversight of the engine: it compares strings, not concepts. Semantic search turns every text into a vector of numbers, such that texts with close meanings sit close together, and searches by proximity. The gain is real, but it has a less-told cost: proximity search is weak precisely on the exact reference ("art. 1453 c.c.", "D.Lgs. 231/2001") that a lawyer looks for all the time.
This article builds the part that can be run with the standard library alone (BM25 lexical search, the fusion of rankings, the validation of ECLI identifiers) and shows with real numbers where keyword search fails. The part that requires an embedding model and a vector index is given as an outline to adapt: I could not run it on this machine, so I report no performance, latency or comparisons between models. For the previous step, reading a scanned document, see from OCR to understanding.
Lexical search, and its two measured flaws
BM25 gives each document a score for the query by summing, for each word of the query, a weight that grows with
the frequency of the word in the document and decreases with its spread across the corpus; the factor b
normalizes for length. The listing implements it on a corpus of four invented "maxims" (short statements of a
legal principle) made up for teaching: they are not real judgments. They are kept in Italian, because the point
of the example is Italian legal vocabulary and Italian references. In order: d1 says that an essential mistake
about the content of the contract makes it voidable; d2, the producer's liability for defects in the goods sold;
d3, termination for breach under art. 1453 of the Italian Civil Code (c.c.) and restitution of
performances; d4, the administrative liability of entities under Legislative Decree 231/2001 (D.Lgs.).
The tokenizza function does work that weighs as much as the ranking: it replaces legal references with a single token
(art_1453, dlgs_231_2001), so that they do not break into scattered numbers.
import math
import re
from collections import Counter
CORPUS = {
"d1": "L'errore essenziale sul contenuto del contratto ne determina l'annullabilità.",
"d2": "Responsabilità del produttore per i vizi del bene venduto.",
"d3": "Risoluzione per inadempimento ai sensi dell'art. 1453 c.c. e restituzione delle prestazioni.",
"d4": "Responsabilità amministrativa degli enti ai sensi del D.Lgs. 231/2001.",
}
def tokenizza(testo: str) -> list[str]:
t = re.sub(r"art\.\s*(\d+)", r"art_\1", testo.lower()) # 'art. 1453' -> 'art_1453'
t = re.sub(r"d\.lgs\.\s*(\d+)/(\d+)", r"dlgs_\1_\2", t) # 'D.Lgs. 231/2001' -> 'dlgs_231_2001'
return [p for p in re.findall(r"[a-zàèéìòù0-9_]+", t) if len(p) > 2]
def tokenizza_ingenua(testo: str) -> list[str]:
"""Common and fragile version: the '/' splits the number and a token cannot start with a digit."""
t = re.sub(r"d\.lgs\.\s*(\d+/\d+)", r"dlgs_\1", testo.lower())
return re.findall(r"\b[a-z_àèìòù][a-z0-9_àèìòù]*\b", t)
class BM25:
def __init__(self, documenti: dict[str, str], k1: float = 1.5, b: float = 0.75):
self.k1, self.b = k1, b
self.token = {d: tokenizza(t) for d, t in documenti.items()}
self.lung_media = sum(map(len, self.token.values())) / len(self.token)
self.df = Counter(t for toks in self.token.values() for t in set(toks))
def punteggio(self, query: str, doc: str) -> float:
toks, tf, n = self.token[doc], Counter(self.token[doc]), len(self.token)
s = 0.0
for q in set(tokenizza(query)):
if q not in tf:
continue
idf = math.log(1 + (n - self.df[q] + 0.5) / (self.df[q] + 0.5))
s += idf * tf[q] * (self.k1 + 1) / (tf[q] + self.k1 * (1 - self.b + self.b * len(toks) / self.lung_media))
return s
def classifica(self, query: str) -> list[tuple[str, float]]:
r = sorted(((d, self.punteggio(query, d)) for d in self.token), key=lambda x: -x[1])
return [(d, round(s, 2)) for d, s in r]
if __name__ == "__main__":
bm25 = BM25(CORPUS)
for numero in ("231/2001", "231/2002"):
print(f"naive D.Lgs. {numero} ->", tokenizza_ingenua(f"D.Lgs. {numero}"))
print("tokenization:", tokenizza("ai sensi del D.Lgs. 231/2001 e dell'art. 1453 c.c."))
for query in ("art. 1453 c.c.", "D.Lgs. 231/2001", "vizio del consenso nel negozio", "vizi del bene"):
print(f"{query!r:<36} {bm25.classifica(query)[:2]}")
# Output (executed):
# naive D.Lgs. 231/2001 -> ['dlgs_231']
# naive D.Lgs. 231/2002 -> ['dlgs_231']
# tokenization: ['sensi', 'del', 'dlgs_231_2001', 'dell', 'art_1453']
# 'art. 1453 c.c.' [('d3', 1.14), ('d1', 0.0)]
# 'D.Lgs. 231/2001' [('d4', 1.28), ('d1', 0.0)]
# 'vizio del consenso nel negozio' [('d2', 0.51), ('d4', 0.38)]
# 'vizi del bene' [('d2', 2.92), ('d4', 0.38)]
The first two output lines show the flaw of a naive tokenization, a very common one: the character
/ splits the number and a token cannot start with a digit, so "D.Lgs. 231/2001" and
"D.Lgs. 231/2002" become the same token dlgs_231. The engine does not tell two different laws apart.
The listing's version keeps the year in the token and the queries on exact references (art. 1453 c.c.,
D.Lgs. 231/2001) immediately find the right document, d3 and d4. This is BM25's strength and the
reason it should not be abandoned.
The second flaw is in the last lines. The query "vizio del consenso nel negozio" (defect of consent in the transaction) should lead to document d1 (essential mistake, voidability), but d1 does not even appear among the first two: the first is d2, which has a score of 0.51 only because it contains the word "del". None of the meaningful words of the query appears in the corpus in the same form ("vizio" is not "vizi", singular against plural), and the stop words, not removed, become signal. A real lexical engine has stemming or lemmatization and a list of stop words, but the vocabulary gap ("consenso", consent, against "errore", mistake) remains: it is what semantic search aims to bridge.
The semantic part: embeddings and index, as an outline
An embedding model associates a vector with a text. You normalize the vector and search by inner product, which
with normalized vectors coincides with the cosine. The
FAISS documentation
lists IndexFlatIP as exact search by inner product, suitable for the cosine too if you normalize
first: it is the right choice to start with, and for a small corpus it is enough. Approximate indexes (IVF, HNSW)
are needed when exact search becomes too slow; they trade some recall for speed, and their tuning must be
measured on your corpus.
import faiss
import numpy as np
from sentence_transformers import SentenceTransformer
modello = SentenceTransformer("intfloat/multilingual-e5-large") # E5 models require the prefixes
massime = ["L'errore essenziale sul contenuto del contratto ne determina l'annullabilità.",
"Responsabilità del produttore per i vizi del bene venduto."]
vettori = modello.encode([f"passage: {m}" for m in massime], normalize_embeddings=True)
indice = faiss.IndexFlatIP(vettori.shape[1]) # exact search; with normalized vectors the inner product is the cosine
indice.add(np.asarray(vettori, dtype="float32"))
domanda = modello.encode(["query: vizio del consenso nel negozio"], normalize_embeddings=True)
punteggi, posizioni = indice.search(np.asarray(domanda, dtype="float32"), 2)
# Not run: sentence-transformers and faiss are not installed on this machine. Outline to adapt.
In the outline, the detail that gets forgotten is the prefix: the
E5 model card
says that every text must begin with query: or passage: , even for non-English texts.
Without the prefixes the vectors are computed all the same and the system works worse without reporting errors. I
do not say by how much: the measurement must be done on your corpus. Two design decisions come before indexing:
the judgment is split into parts (maxim, facts, reasoning, ruling) because a single vector for a long text
dilutes the meaning, and each part carries with it the metadata (judge, date, identifier) needed for
filtering. The date matters more than it seems: a judgment on repealed rules may be irrelevant, and the
time filter goes in the query.
Merging the two rankings: RRF fusion and its limit
To combine the lexical ranking and the semantic one, Reciprocal Rank Fusion is often used, described by Cormack, Clarke and Büttcher: the score of a document is the sum, over every ranking, of 1 divided by (k plus the position), with k set to 60 by the authors after a preliminary investigation. It uses only the positions, not the raw scores, which have different scales and are not comparable. A note: the weights 0.6 and 0.4 seen in some implementations are not part of the original formula and are an addition that needs to be justified with a measurement.
def rrf(classifiche: list[list[str]], k: int = 60) -> list[tuple[str, float]]:
"""Reciprocal Rank Fusion: score(d) = sum over every ranking of 1 / (k + position of d)."""
punti: dict[str, float] = {}
for classifica in classifiche:
for posizione, doc in enumerate(classifica, start=1):
punti[doc] = punti.get(doc, 0.0) + 1.0 / (k + posizione)
return sorted(((d, round(p, 4)) for d, p in punti.items()), key=lambda x: -x[1])
if __name__ == "__main__":
# Query: "vizio del consenso nel negozio". The first list is the lexical (BM25) one from the previous example;
# the second is a SEMANTIC ranking written by hand as a stand-in for a vector index (no model was run).
lessicale = ["d2", "d4", "d1", "d3"]
semantica = ["d1", "d2", "d3", "d4"]
print("lexical only :", lessicale)
print("semantic only:", semantica)
print("RRF k=60 :", rrf([lessicale, semantica]))
print("RRF k=1 :", rrf([lessicale, semantica], k=1))
# Output (executed):
# lexical only : ['d2', 'd4', 'd1', 'd3']
# semantic only: ['d1', 'd2', 'd3', 'd4']
# RRF k=60 : [('d2', 0.0325), ('d1', 0.0323), ('d4', 0.0318), ('d3', 0.0315)]
# RRF k=1 : [('d2', 0.8333), ('d1', 0.75), ('d4', 0.5333), ('d3', 0.45)]
The listing merges the real BM25 ranking of the previous example with a hand-written semantic ranking (a stand-in: no model was run) in which d1 is first. The result is instructive and not flattering: with k = 60 document d2 stays first (0.0325 against 0.0323), because with a large k the positions weigh almost the same and a semantic second place almost equals a first place. With k = 1, d2 wins by a wider margin (0.83 against 0.75). So fusion does not repair a polluted lexical ranking: the lexical part must be cleaned first (stop words, stemming), then you merge, and quality is measured on a set of queries with known answers, not on a single example.
The ECLI identifier: how to validate it without making things up
To cite a judgment in a stable way there is the European Case Law Identifier. The
page of the European e-Justice portal
describes it as made of five mandatory elements separated by colons: the ECLI acronym, the country code, the court
code, the year of the decision and an ordinal number of up to 25 alphanumeric characters in the format chosen by
each State (dots are allowed, other punctuation is not). Its example, declared non-existent, is
ECLI:NL:HR:2009:384425. I did not verify the format of the Italian number, so the examples here
do not claim to be real identifiers.
import re
# Structure: ECLI : country : court : year : number (max 25 alphanumeric characters, dots allowed). The two country letters and the 4 year digits are my assumption
ECLI = re.compile(r"^ECLI:([A-Z]{2}):([A-Z0-9]+):(\d{4}):([A-Za-z0-9.]{1,25})$")
def analizza(ecli: str) -> dict | None:
m = ECLI.match(ecli)
if not m:
return None
return dict(zip(("country", "court", "year", "number"), m.groups()))
for prova in ("ECLI:NL:HR:2009:384425", "ECLI:XX:AB:2024:EXAMPLE.12", "ecli:it:cass:2024:1", "ECLI:IT:CASS:24:1",
"ECLI:IT:CASS:2024:" + "9" * 26):
print(f"{prova[:34]:<36} {analizza(prova)}")
# Output (executed):
# ECLI:NL:HR:2009:384425 {'country': 'NL', 'court': 'HR', 'year': '2009', 'number': '384425'}
# ECLI:XX:AB:2024:EXAMPLE.12 {'country': 'XX', 'court': 'AB', 'year': '2024', 'number': 'EXAMPLE.12'}
# ecli:it:cass:2024:1 None
# ECLI:IT:CASS:24:1 None
# ECLI:IT:CASS:2024:9999999999999999 None
The output accepts the two well-formed identifiers and rejects the other three: the lowercase acronym, the two-digit year and a number of 26 digits. A caution about the code: the structure is checked, not the existence: a formally valid ECLI may correspond to no judgment, and a link to a database must be built with the address that database publishes, not guessed. For judgments of the European Union the official source is EUR-Lex; for national ones, check the conditions and the reuse licence of each database before indexing it, because not all of them allow bulk processing.
What you can do now
You know why a keyword search fails on vocabulary but excels on exact references, and you have seen with real numbers that a naive tokenization confuses two different decrees. You can build an RRF fusion and you know that with a large k it does not correct a dirty ranking. You know which details make an embedding model work badly without errors (the prefixes, the non-normalized vectors) and how to validate the shape of an ECLI. What is missing is the measurement that matters: a set of queries with known answers on your corpus, against which to compare lexical, semantic and fusion. To build on top of this search an assistant that answers citing its sources, continue with the Legal AI Assistant; for the personal data present in judgments, see GDPR and privacy by design.
Frequently asked questions
Why is vector search not enough for searching case law?
Because it is weak on exact references, such as an article or decree number, where lexical search is precise. A hybrid search combines the two, but the fusion must be tuned and measured on queries with known answers.
What is Reciprocal Rank Fusion?
It is a method for combining several rankings using only the positions: the score of a document is the sum of 1 divided by (k plus the position) over every ranking, with k set to 60 in the original paper. It does not require comparing scores with different scales.
What does an ECLI look like?
It has five elements separated by colons: the ECLI acronym, the country code, the court code, the year of the decision and an ordinal number of up to 25 alphanumeric characters, whose format is decided by each Member State.
Before this article in the series: Summarizing Legal Documents with AI: Chunking and Map-Reduce. Next in the series: E-Signature and Document Authentication at Scale.
Sources
- Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods - the RRF formula and the value k = 60, paper text read on 2026-11-12
- e-Justice: European Case Law Identifier (ECLI) - the five elements of the ECLI and the 25-character limit for the number, consulted on 2026-11-12
- Model card of multilingual-e5-large - the requirement of the
query:andpassage:prefixes, consulted on 2026-11-12 - FAISS: available indexes -
IndexFlatIPas exact inner-product search suitable for the cosine with normalized vectors, consulted on 2026-11-12
The three listings marked "Output (executed)" were run with Python 3 and the standard library only; the four maxims of the corpus are invented for the exercise and the semantic ranking in the fusion is written by hand. The outline with embeddings and FAISS was not run, so the article reports no measurement of performance, latency or model quality. No part is legal advice.
Commenti
Caricamento commenti...
Sign in to comment