RAG for Legal Document Search: A Developer's Guide
Build RAG search over legal documents: clause-aware chunking, hybrid keyword and vector search, citation checks, access control and lawyer review.
Retrieval-augmented generation (RAG) for legal work looks like any other RAG project on a whiteboard: split documents, index them, retrieve passages, ask a model to answer from them. In practice three things make it harder. Legal text has a structure that carries meaning, every answer has to point to the passage it came from, and a made-up citation is a professional problem, not just a bad answer. This guide covers how to handle each one, using official documentation for the search engines and public legal data sources involved. It is a developer guide, not legal advice; the professional rules that apply to your users depend on their jurisdiction.
Chunk along the document’s own structure
Fixed-size chunks cut a clause in half and separate a definition from the sections that use it. For contracts, statutes and judgments, split on the units the author already created: articles, sections, numbered clauses, schedules, and paragraphs of a judgment. Keep each chunk small enough to cite, and store metadata alongside the text:
- the document ID and version (or date of the consolidated text)
- the heading path, such as “Part 3 > Section 12 > (b)”
- the clause or paragraph number exactly as printed
- character offsets of the chunk within the source file
- the matter, client or workspace it belongs to, for access control
Defined terms deserve special handling. If clause 14 uses “Confidential Information”, retrieval should be able to pull in the definition clause too, either by linking chunks through metadata or by adding the definition to the prompt when the term appears. How much context to send back to the model is a separate tuning problem, covered in our guide to RAG context window management.
Public sources often arrive already structured, which saves parsing work. GovInfo stores its content as self-describing packages, and its API can list the granules (smaller parts) inside a package, so you can index at the granule level instead of the whole publication.
Use hybrid keyword and vector search
Lawyers search for exact strings: a section number, a party name, a defined term, a citation such as “576 U.S. 644”. Embedding search is weak at exact matches but good at plain-language questions like “can the supplier end the contract early”. Run both and merge the results.
| Engine | How it merges keyword and vector results |
|---|---|
| Elasticsearch | An rrf retriever combines two or more child retrievers (for example BM25 and a semantic query) with reciprocal rank fusion; rank_constant defaults to 60 |
| OpenSearch | A search pipeline normalizes and combines scores at query time; a score ranker processor can use rank-based RRF instead |
| Qdrant | The Query API runs prefetch sub-queries (dense, sparse or BM25) and fuses them with rrf or dbsf |
Reciprocal rank fusion looks only at where each document ranks in each list, not at the raw scores, so you don’t have to calibrate BM25 scores against cosine similarity before you start. Elastic’s documentation says RRF “requires no tuning”. Begin there, then measure against your own test questions (see the evaluation section) before you try weighted score fusion.
Apply filters for jurisdiction, document type, date and matter during retrieval, not afterwards. We cover the mechanics in metadata filtering in vector search.
Cite the exact passage
Every sentence the model writes should trace back to a retrieved chunk. A pattern that works:
- Give the model numbered passages, each with its document ID, clause number and offsets.
- Ask for an answer in which every claim carries one or more passage numbers.
- After generation, check in code that each cited passage number exists in the retrieved set, and that any quoted text appears verbatim in that passage.
- Render citations as links that open the source document at the stored offset, so a reviewer sees the clause in context.
If step 3 fails, don’t show the answer. Return the passages instead and say the model’s answer could not be verified.
Check case citations against a real database
Generated answers about case law may cite cases from the model’s training data rather than from your index. Those citations need an outside check. Free Law Project’s CourtListener has a citation lookup API built for this; its docs describe it as a possible guardrail against hallucinated citations. This is the official example:
curl -X POST "https://www.courtlistener.com/api/rest/v4/citation-lookup/" \
--header 'Authorization: Token <your-token-here>' \
--data 'text=Obergefell v. Hodges (576 U.S. 644) established the right to marriage among same-sex couples'
The response lists each citation found, its position in the text, and a status: 200 when it matched a decision, 404 when the citation is well formed but not in CourtListener, 400 when the reporter is unknown, and 300 when it matches more than one decision. Treat anything other than 200 as a blocker for human review.
Know the limits. The API skips statutes, law journals, and id. and supra citations, and it won’t match citations missing a volume or page number. A text request can hold at most 64,000 characters. A 200 also means only that the case exists; it says nothing about whether the case supports the proposition. That still needs a person.
Why verification is not optional
Courts have started dealing with fabricated authorities in filings. In R (Ayinde) v London Borough of Haringey [2025] EWHC 1383 (Admin), the Divisional Court of England and Wales heard referrals arising from lawyers’ suspected use of generative AI that put false citations and quotations before the court. The judgment says freely available generative AI tools “are not capable of conducting reliable legal research”, and that lawyers who use AI for research must check it against authoritative sources, naming the government’s legislation database and the National Archives judgment database among them. It lists the court’s powers when those duties are breached, including referral to a regulator and contempt proceedings.
Your users may also face court-specific or judge-specific rules about AI in filings. Those vary, so design the tool to make verification and disclosure easy rather than coding in any single rule.
For a developer, the lesson is concrete: build the citation check, show unverified output as unverified, and log who reviewed what.
Permissions, privilege and confidentiality
A legal RAG system will hold privileged and confidential material from many matters. Retrieval must respect the same walls the document management system does, because a model can summarize a passage the user was never allowed to open.
- Enforce access in the search layer. Elasticsearch supports document level security, which limits which documents a role can read, and field level security, which limits which fields it sees. Its docs say these features are intended for read-only accounts.
- Filter on every query. In Qdrant, payload filters with
must,shouldandmust_notclauses can restrict results to the user’s matters. Qdrant recommends creating payload indexes for filtered fields, ideally before ingesting data. The filter is only as good as the code that builds it, so derive it from the authenticated user on the server, never from the request body. - Watch what leaves your network. The Ayinde judgment points to UK judicial guidance that says not to enter non-public information into a public AI tool. The same applies to third-party APIs: CourtListener logs API queries under its privacy policy (you can disable this in your profile), and for semantic search it lets you send a precomputed embedding by POST instead of the query text.
Public legal data sources
| Source | What you get | Access |
|---|---|---|
| CourtListener REST API (v4) | Case law search with keyword and semantic modes; citation lookup | API token |
| GovInfo API | Official U.S. federal publications from all three branches, including court opinions (USCOURTS collection), with search, collection and related-content services | api.data.gov key |
| EUR-Lex web service | Queries over EU law with expert-search options, including full text, returned as XML | Free after registration (SOAP) |
Some practical notes from the docs. CourtListener handles API searches with keyword search unless you ask for semantic results, and semantic search covers case law only. GovInfo’s related service links a bill to its versions, history and public law, which helps you keep amendments together. The EUR-Lex web service can’t download document files itself; you fetch those by identifier through the Cellar RESTful API or stable links.
Evaluate with lawyers in the loop
Generic RAG metrics won’t tell you whether the tool is safe to hand to a lawyer. Build an evaluation set with the people who will use it:
- Collect real questions. Ask lawyers for questions they actually research, along with the clauses or authorities a correct answer must cite.
- Score retrieval separately. For each question, check whether the required passages appear in the top results. Most bad answers start as a retrieval miss.
- Score citations mechanically. Count answers with a citation that fails your passage check or the citation lookup. Any non-zero count is a bug to fix, not a figure to report.
- Have lawyers grade the answers. Ask whether each answer is correct, complete, and supported by the cited passages, and record their comments.
- Rerun after every change to chunking, embeddings, fusion settings or prompts, and keep the history.
Contract review raises its own questions about clause extraction and playbooks; our guide to AI contract review agents covers them. If you’d rather start from a framework than wire the pipeline yourself, see our listings for LlamaIndex and R2R.
Written by AI Agents Directory
Editorial team
Facts in this guide are checked against official documentation and repositories, which are linked in the article.