Legal search
Legal search turns court opinions, RECAP case records, oral arguments, people, positions, and parenthetical groups into searchable views. Django records remain the source of truth. Elasticsearch provides fast text, relationship, and vector search, while the web site, APIs, feeds, exports, and alerts present the results through different interfaces.
The Search and notifications page gives the wider product context. User alerts explains the saved-query and alert-delivery side of search.
Search data model
Source records
The search system keeps legal records in Django models and creates indexed documents for the fields needed by search. An indexed document is a search view of a source record. It carries searchable text, exact values, dates, links, highlights, and relationship IDs without replacing the source record.
The search types cover these user goals:
- Case-law search over opinion clusters and their opinions.
- RECAP search over dockets and their filings.
- RECAP docket search over case-level data.
- RECAP document search over individual filings.
- Oral-argument search over audio and transcript data.
- People search over people and their positions.
- Parenthetical search over grouped explanatory text.
Each search type combines natural text with structured values such as court, docket number, citation, status, and date. This lets one query support broad discovery and focused legal research. Opinion content also records its source, extraction method, and main-version status so the selected text has clear provenance. cl/…/models.py• L3559-3649, cl/…/documents.py• L112-258, cl/…/documents.py• L1148-1404
Court data defines which jurisdictions can be searched. A source-specific record can join the search system without changing the main result model. cl/…/forms.py• L602-652, cl/…/documents.py• L257-545
References: cl/…/models.py• L3559-3649 cl/…/documents.py• L112-258 cl/…/documents.py• L257-545 cl/…/documents.py• L1148-1404 cl/…/forms.py• L602-652
Parent-child records
Some indexed records are parents that collect related child records. An opinion cluster contains opinions. A docket contains RECAP documents. A person contains positions. Elasticsearch can match a child while returning the parent as the main result.
This relationship keeps result lists useful to people. A search can show one case, docket, or person and still identify the opinion, filing, or position that matched. Child IDs and routing keep records from different parents separate. cl/…/documents.py• L587-616, cl/…/documents.py• L726-727, cl/…/documents.py• L1148-1153
References: cl/…/documents.py• L587-616 cl/…/documents.py• L726-727 cl/…/documents.py• L1148-1153 cl/…/tasks.py• L2226-2270
Docket source identity
RECAP-style search uses one shared result shape for docket sources. A source definition says which dockets and documents belong to that source, when the source is ready to index, how child IDs are named, and whether it supports alert matching.
The source boundary protects identity and visibility. Separate namespaces prevent a Supreme Court record from replacing a RECAP record with the same database key. A record can remain searchable when its provider download URL is blank. Result views show a link only when one exists. cl/…/documents.py• L1330-1404, cl/…/documents.py• L1405-1480
References: cl/…/documents.py• L1330-1404 cl/…/documents.py• L1405-1480 cl/…/es_docket_sources.py• L31-97 cl/…/es_docket_sources.py• L149-181
Elasticsearch search system
Index boundaries
Elasticsearch separates large record families into indexes. Case law uses parent and child opinion documents. RECAP uses parent docket documents and child filing documents. People, oral arguments, parenthetical groups, and alert queries have their own index roles.
These index roles are shared contracts. Document definitions, query builders, background jobs, and deployment settings must agree on index names and settings. A mismatch can make records disappear from search or stop new records from being indexed. cl/…/documents.py• L400-547, cl/…/documents.py• L801-1146, cl/…/documents.py• L1405-1480
References: cl/…/es_indices.py• L6-72 cl/…/documents.py• L400-547 cl/…/documents.py• L801-1146 cl/…/documents.py• L1405-1480 cl/…/apps.py• L14-73
Query filters
SearchForm is the shared boundary between a request and a search query. It selects the search type, cleans field names, normalizes dates, applies court and status choices, and rejects invalid input before Elasticsearch sees it.
The form exposes fields that match the user's search goal:
| Search family | Main filter groups |
|---|---|
| Opinions | Court, judge, status, citation, filing date, docket number, citation count |
| RECAP | Court, case name, docket number, filing dates, entry dates, parties, attorneys, document data, availability |
| Oral arguments | Court, judge, case name, docket number, argument dates |
| People | Name, birth data, school, appointment, political affiliation, position data |
| Parentheticals | Court, docket number, filing date, parenthetical text |
The form displays filters for the selected scope. Date controls accept calendar dates and, where enabled, relative dates. Partial dates become ranges with a floor or ceiling. Empty court and status selections receive safe defaults so a query does not silently return no records. cl/…/forms.py• L60-152, cl/…/forms.py• L299-399, cl/…/forms.py• L674-814
The REST model endpoints use separate filters for database records. Search result endpoints use the shared search language because their results come from indexed documents rather than normal model querysets. cl/…/forms.py• L863-1170, cl/…/filters.py• L28-100
References: cl/…/forms.py• L60-152 cl/…/forms.py• L299-399 cl/…/forms.py• L674-814 cl/…/forms.py• L863-1170 cl/…/fields.py• L32-122 cl/…/filters.py• L28-100
Text and semantic search
Keyword search matches analyzed text and exact subfields. Relevance can favor fields that help identify a legal record. Related searches use opinion content to find similar cases while excluding the cases used as the starting point.
Semantic search adds vector matching to opinion text. Opinion text is split into chunks with embeddings. A semantic result returns the relevant chunk so the reader can see the part that matched. The V4 API accepts the vector in the request body and permits semantic search only for opinions. cl/…/api_views.py• L638-695, cl/…/documents.py• L2280-2326, cl/…/tasks.py• L2226-2270
Text choice has a clear source boundary. The system can store several opinion content versions and mark one as the main version. Search and embedding work use the selected clean text. This lets a missing or failed derived artifact limit one search feature without changing the source record. cl/…/models.py• L3559-3649, cl/…/factories.py• L209-220
References: cl/…/api_views.py• L638-695 cl/…/documents.py• L2280-2326 cl/…/models.py• L3559-3649 cl/…/tasks.py• L1941-2054 cl/…/tasks.py• L2226-2270 cl/…/factories.py• L209-220
Pagination and result preparation
The V3 API and web search use page numbers. The V4 API uses a cursor with a stable sort and a unique tie-breaker. This lets clients move through changing result sets without relying on a deep offset.
Results are prepared after Elasticsearch returns them. The search layer attaches child matches, merges highlights, fills fields that are not exposed by the index, adds semantic chunks when needed, and keeps cached results in the same shape as live results.
The API fetches one extra result to decide whether another cursor page exists. It removes that result before serialization. Backward pages are reversed so clients see the same order in both directions. cl/…/api_utils.py• L217-237, cl/…/api_utils.py• L250-370, cl/…/api_utils.py• L372-476, cl/…/api_utils.py• L549-575
References: cl/…/api_utils.py• L53-105 cl/…/api_utils.py• L217-237 cl/…/api_utils.py• L250-370 cl/…/api_utils.py• L372-476 cl/…/api_utils.py• L505-531 cl/…/api_utils.py• L549-575
Search interfaces
Web result views
The web search is the main human-facing interface. A request with no parameters opens the search home page. A request with search parameters runs the selected search and renders the result list. A POST can create or edit a saved alert from the same search intent.
The result view presents parent records first and matched child records below them. This gives a case, docket, or person context first and the matching text, filing, or position detail second. The home page also reports broad corpus and activity measures without changing the result set. cl/…/views.py• L83-127, cl/…/views.py• L143-327, cl/…/search_result.html• L6-43, cl/…/utils.py• L52-77
The web entry point can route an empty request to a newer home page when its feature flag is active. Parameterized searches keep the shared result flow. cl/…/views.py• L90-113, cl/…/views.py• L150-202
References: cl/…/views.py• L83-127 cl/…/views.py• L143-327 cl/…/v2_homepage.html• L23-200 cl/…/search.html• L56-242 cl/…/search_result.html• L6-43 cl/…/utils.py• L52-77
API result rendering
The API has two layers. Model endpoints expose source records through REST serializers and database filters. Search endpoints expose Elasticsearch results through serializers that add highlights, nested child matches, metadata, links, and scores.
V3 returns page-based results and allows public search subject to API limits. V4 requires authentication and uses cursor pagination. V4 also returns separate keyword and semantic score data when semantic search is active. Opinion model responses support JSON, the browsable API, and XML. The safe XML renderer removes invalid control characters and records affected IDs for later repair. cl/…/api_views.py• L442-483, cl/…/api_views.py• L520-635, cl/…/api_views.py• L638-695, cl/…/api_renderers.py• L15-66
Result serializers preserve the parent-first view. Opinion clusters include nested opinions. RECAP results include nested filings. People results include nested positions. This keeps the public response aligned with the way the query matched the corpus. cl/…/api_views.py• L529-554, cl/…/api_utils.py• L452-469
References: cl/…/api_views.py• L442-483 cl/…/api_views.py• L520-635 cl/…/api_views.py• L638-695 cl/…/api_renderers.py• L15-66 cl/…/api_serializers.py• L382-562 cl/…/api_serializers.py• L593-866
Feeds and exports
Search feeds reuse the Elasticsearch query path and return small Atom feeds. A custom feed returns opinion clusters or RECAP documents. Court feeds return opinions for one court or for all courts. A child filing without its own page links to its docket entry instead.
Feeds use filing dates that fit the record family. RECAP entries use the filing time in the court's time zone when needed. Feed text is cleaned before XML output so source control characters do not invalidate the feed. Invalid search syntax returns a client error. Elasticsearch transport failures return a service error. cl/…/feeds.py• L52-86, cl/…/feeds.py• L89-198, cl/…/feeds.py• L200-295, cl/…/feeds.py• L299-332
Search exports run as background work. The request queues a task. The task validates the saved query again, fetches matching records, flattens parent and child results into CSV rows, applies the document family's public field shape, and emails the file to the user. cl/…/feeds.py• L89-163, cl/…/tasks.py• L432-523
References: cl/…/feeds.py• L52-86 cl/…/feeds.py• L89-198 cl/…/feeds.py• L200-332 cl/…/tasks.py• L432-523 cl/…/documents.py• L1415-1480
Opinion clustering and legal relations
Opinion cluster results
An opinion cluster is the result-level unit for case-law search. It groups the opinions for one case and carries shared case data such as the case name, court, filing date, judges, citations, status, docket, and source provenance. The child opinion carries the decision text and opinion-specific data.
The source value records where case-law content came from. When sources merge, the value keeps a stable combined form and can become a readable label in exports and other result views. External case metadata and source files can add content without changing the cluster identity. cl/…/models.py• L2413-2520, cl/…/documents.py• L2597-2692
References: cl/…/models.py• L2413-2520 cl/…/documents.py• L2597-2692 cl/…/factories.py• L222-283
Citation and related results
Search can resolve a citation to a matching case and can show citation depth when a query asks which cases cite another case. A related query uses opinion content to find similar clusters while excluding the source clusters.
Parenthetical search uses the opinion cluster as its grouping key. It presents representative explanatory text and connects the reader to more matching parentheticals for that case. These paths add legal relationships to ordinary text search without changing the main result unit. cl/…/documents.py• L113-255, cl/…/pa_search_result.html• L6-51
References: cl/…/search_utils.py• L235-275 cl/…/elasticsearch_utils.py• L1520-1542 cl/…/elasticsearch_utils.py• L1913-1976 cl/…/documents.py• L113-255 cl/…/pa_search_result.html• L6-51
Asynchronous indexing
Change propagation
Search indexing is separate from the database transaction. Model changes queue work that reads the latest database state and rebuilds the affected search view. The same idea covers saves, deletes, relation changes, and changes to records that contribute fields to a parent or child.
The relationship maps are the key to propagation. A docket change can update the docket and its filings. A cluster change can update the cluster and its opinions. Changes to judges, citations, parties, metadata, or docket entries can change search results even when the main indexed model did not change.
Docket numbers also have a derived search value. A cleaning task can use structured model review for hard federal appellate cases. Its response has a fixed shape and the save step checks that the source record did not change while cleaning was in progress. The raw value stays available for source fidelity. cl/…/llm_models.py• L8-34, cl/…/tasks.py• L2277-2350
References: cl/…/signals.py• L64-80 cl/…/signals.py• L315-373 cl/…/signals.py• L375-495 cl/…/signals.py• L497-659 cl/…/llm_models.py• L8-34 cl/…/tasks.py• L2277-2350
Parent and child indexing
Background tasks create parent documents before child documents and route each child to its parent. They support full parent-and-child indexing, targeted repairs, partial updates, bulk writes, and deletion. Retry paths isolate connection, timeout, conflict, and missing-document failures.
The sweep indexer provides recurring corpus-wide repair. It processes supported model families in chunks, checks for missing documents when requested, records its position in Redis, and resumes after interruption. This keeps long repair cycles from requiring a full restart. cl/…/sweep_indexer.py• L175-229, cl/…/sweep_indexer.py• L231-445, cl/…/tasks.py• L212-337, cl/…/tasks.py• L526-637
References: cl/…/tasks.py• L212-337 cl/…/tasks.py• L526-637 cl/…/tasks.py• L809-947 cl/…/tasks.py• L1070-1138 cl/…/sweep_indexer.py• L175-229 cl/…/sweep_indexer.py• L231-445
Source acquisition
Searchable content can arrive through external legal-data sources before it becomes complete in the local database. PACER bulk fetch work selects unavailable RECAP documents and sends one fetch at a time per court. A later processing stage extracts text from successful downloads.
The fetch loop records pending and failed work separately from the source document. It uses per-court spacing, exponential backoff, retry limits, and a stale-request cutoff. A blocked court therefore does not stop work for every other court. cl/…/pacer_bulk_fetch.py• L214-294, cl/…/pacer_bulk_fetch.py• L296-352, cl/…/pacer_bulk_fetch.py• L388-519
References: cl/…/pacer_bulk_fetch.py• L214-294 cl/…/pacer_bulk_fetch.py• L296-352 cl/…/pacer_bulk_fetch.py• L388-519 cl/…/pacer_bulk_fetch.py• L521-560
Text and embedding work
Document text becomes searchable after download and extraction. A token-count command samples opinion and RECAP text to estimate corpus size. Embedding generation selects eligible opinions, groups them under a token limit, calls an embedding service, stores the chunks outside the database, and later adds them to opinion child documents.
The pipeline has useful intermediate states. A record can be searchable before embeddings finish. Missing text, missing embeddings, or a failed external service delays only the related capability. cl/…/cl_compute_token_count.py• L16-39, cl/…/cl_compute_token_count.py• L155-249, cl/…/generate_opinion_embeddings.py• L101-124, cl/…/generate_opinion_embeddings.py• L126-235, cl/…/tasks.py• L2017-2270
References: cl/…/cl_compute_token_count.py• L16-39 cl/…/cl_compute_token_count.py• L155-249 cl/…/generate_opinion_embeddings.py• L101-124 cl/…/generate_opinion_embeddings.py• L126-235 cl/…/tasks.py• L2017-2270 cl/…/models.py• L3559-3649
Sealing and removal
Sealing protects access to records while keeping search state consistent. A sealed RECAP document keeps its row but loses files and text. A sealed opinion cluster is removed and leaves a redirection record so old links return the correct gone or moved response.
Cleanup also removes citations mined from sealed text and updates the search child document. Separate removal tasks handle records that should no longer appear in an index. cl/…/tasks.py• L1816-1893, cl/…/api_views.py• L323-362
References: cl/…/tasks.py• L1816-1893 cl/…/api_views.py• L323-362 cl/…/deletion_utils.py• L1-16 cl/…/deletion_utils.py• L72-170 cl/…/deletion_utils.py• L391-417
Change checklist
When these files or sections are changed, remember to consider these:
- Keep each search type aligned across
SEARCH_TYPES,SearchForm, document selection, query construction, result serializers, result templates, feeds, and CSV export. - Keep parent-child names, child ID namespaces, routing, unique-count fields, and source ownership aligned across document definitions, query builders, API processing, and indexing tasks.
- When a source field changes, update the signal map and every parent or child propagation path that copies that field.
- Treat result field names, highlight shapes, nested child names, score metadata, cursor behavior, and CSV headers as public contracts.
- Keep semantic search rules aligned across embedding storage, the opinion mapping, form validation, API validation, vector queries, and chunk rendering.
- When a docket source changes, update its court scope, readiness rule, ID namespace, visibility, and alert behavior together.
- When a docket number rule changes, keep raw values, cleaned values, search fields, and the structured cleaning response aligned.
- When a source file or provider URL changes, check whether the record remains searchable, whether its result link is valid, and whether the parent document needs a refresh.
- When feeds or API XML output change, keep control-character cleanup and the affected-record repair path intact.
- When embedding batches change, keep token limits, cache handoff, object storage paths, index routing, and semantic result rendering aligned.
- When asynchronous fetch or sweep behavior changes, keep per-court pacing, retry state, checkpoints, and downstream extraction or indexing stages aligned.
- When sealing or deleting a source record, check storage cleanup, citation cleanup, search deletion, redirection behavior, and alert matching as one flow.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A parent is missing when a child is indexed | The child cannot join the case, docket, or person result | Parent creation runs before child indexing. Bulk work reports failed IDs. |
| A child ID namespace or routing value differs between paths | A record can be overwritten, hidden, or impossible to update | Source definitions, ID helpers, queries, and tasks share one identity contract. |
| A query contains invalid syntax or an unsupported semantic request | The search fails instead of returning a valid result set | SearchForm and V4 body validation run before query construction. |
| An indexed source field changes without a signal mapping | Search returns stale text or metadata | Save, relation, and repair paths cover the field. |
| A docket number changes during structured cleaning | A newer source value can be replaced by an older derived value | The update checks the source modification time before saving. |
| A cursor sort lacks a stable unique tie-breaker | Results can repeat or disappear between API pages | V4 cursor pagination adds stable ordering and a unique field. |
| A feed or XML result contains invalid control characters | XML output fails or becomes invalid | Feed cleanup and SafeXMLRenderer remove invalid characters before rendering. |
| A PACER fetch remains pending or fails repeatedly | One court can stop making progress or a document remains unavailable | Per-court sequencing, backoff, retry limits, and stale-request cutoffs isolate the blocked fetch. |
| An embedding batch disappears before upload | Opinions have no semantic vectors and the batch cannot be indexed | The handoff uses a temporary cache key and the upload task reports missing batches. |
| A sweep cycle stops after a partial run | Some records remain missing or stale in Elasticsearch | Redis checkpoints let the next cycle resume from the last model and ID. |
| A sealed document keeps citation rows or an indexed child | A sealed filing remains visible through authorities or search | Sealing removes citations and queues the matching search update. |
| The homepage feature flag routes an empty request to an incomplete page | The search landing page loses its entry point or summary data | Only empty GET requests use the flagged route. Parameterized searches keep the result flow. |
Key files
| File | Why to read it |
|---|---|
| cl/…/models.py | Defines source records, opinion content provenance, and the relationships used by search. |
| cl/…/documents.py | Shows the indexed parent and child views for each search family. |
| cl/…/es_indices.py | Defines the Elasticsearch index boundaries. |
| cl/…/es_docket_sources.py | Defines source identity, readiness, court scope, and visibility for docket records. |
| cl/…/forms.py | Defines the common search language and validation rules. |
| cl/…/llm_models.py | Defines the structured contract for cleaned docket numbers. |
| cl/…/api_utils.py | Shows Elasticsearch execution, result enrichment, caching, and cursor page preparation. |
| cl/…/api_views.py | Shows model APIs, V3 search, and V4 cursor and semantic search. |
| cl/…/api_renderers.py | Shows how invalid XML data is cleaned for API output. |
| cl/…/feeds.py | Shows how search results become Atom feeds and how child links fall back to docket entries. |
| cl/…/views.py | Shows homepage routing, web search, alert handling, and export requests. |
| cl/…/tasks.py | Defines asynchronous indexing, exports, embeddings, docket cleaning, and removal. |
| cl/…/sweep_indexer.py | Provides recurring corpus-wide repair with checkpointed progress. |
| cl/…/pacer_bulk_fetch.py | Coordinates rate-limited retrieval and processing of unavailable RECAP documents. |
| cl/…/generate_opinion_embeddings.py | Queues token-limited opinion embedding batches. |
| cl/…/cl_compute_token_count.py | Estimates text size for opinion and RECAP corpora. |
| cl/…/factories.py | Provides test records that model search parents, children, content versions, and embeddings. |
| cl/…/deletion_utils.py | Defines sealing, storage cleanup, citation cleanup, and deletion blockers. |