Generative AI · Chapter 19
RAG on Databricks: AI Search and context engineering
Reviewed by TechFabric engineers. How we write this guide →
Retrieval-augmented generation (RAG) on Databricks means finding the few passages that answer a question in a Unity Catalog table, usually through a Databricks AI Search index (formerly Vector Search) kept in sync with that table, and handing them to the model with the question. Context engineering is the wider job of deciding everything the model reads on each call, instructions, tool definitions and history included, within a fixed token budget.
When an assistant gives a bad answer, the first thing we'd check is what it was given to read, before touching the model or the prompt, because most wrong answers are an information problem. This chapter covers how to build the index, how to chunk, hybrid search and the reranker, how to filter by the person asking, and how to measure retrieval on its own.
The short version
A language model knows nothing about your business until something puts your information in front of it, and the quality of an answer is mostly decided by that step rather than by the model. Retrieval-augmented generation, usually shortened to RAG, is the name for it, and it works by finding the handful of passages most likely to contain the answer and handing them over with the question. Three things make it good. The passages have to be cut up sensibly so each one still makes sense on its own, the search has to be kept up to date automatically so it never returns last quarter's policy as though it were current, and it has to be filtered by who is asking before anything is retrieved rather than afterwards. That last point is a security control rather than a refinement, because anything the search can see should be treated as something the asker has already seen.
The context window is a budget, not a container #
Deciding what goes into that window, and what gets left out of it, has picked up the name context engineering. The name is newer than the practice and it describes something real, which is that the window is a resource with competing claims on it rather than a box you fill with everything available.
The context window is the amount of text a model can consider in one call, and it is easy to read that number as a container waiting to be filled. It behaves much more like a budget, because several things are spending it before your retrieved documents arrive. Every call carries the system instructions, the definitions of any tools the model may call, the retrieved documents, whatever conversation history you are replaying, and the space the answer itself needs. A team that adds twelve tool definitions and a two thousand word style guide has spent a meaningful share of the window before the user has typed anything.
Filling what remains is not free either. Quality degrades once the relevant passage is buried among fifteen irrelevant ones, because every extra near-miss is a chance to attend to the wrong thing. The setting we'd look at first is the result count: twenty results "because more context can't hurt" is the usual starting point, and we'd only keep it if a labelled evaluation set says twenty beats five. Cost scales with the window on every call, so an extra three thousand tokens of boilerplate is a tax paid per request, for the life of the feature, at a volume nobody forecasts correctly.
A worked example makes the point. Take an assistant whose system instructions run to 1,500 tokens, with twelve tool definitions at about 300 tokens each, six replayed turns of history at about 650 each, and a budget of 1,000 tokens for the answer. That's roughly 10,000 tokens spent before retrieval, so five passages of 400 tokens add 2,000 and twenty add 8,000. At 100,000 calls a month, the difference between five and twenty passages is 600 million input tokens a month, and the evaluation set is the only thing that can say whether those tokens bought anything. Cutting the twelve tools to the four this assistant actually needs saves another 240 million at the same volume, which is why we'd audit tool definitions before trimming retrieval.
Databricks AI Search, formerly Vector Search #
Semantic search converts text into a numeric vector whose position encodes meaning, so a question about missed payments finds a passage about arrears without the two sharing a word. Databricks sells this as AI Search, which was called Vector Search until 2026; the Python package is now databricks-ai-search and the client is AISearchClient, so older tutorials that import VectorSearchClient from databricks-vectorsearch are a release behind. The old package still works, and the new client imports from databricks.ai_search.client (create AI Search endpoints and indexes). What matters architecturally is where the index comes from.
A Delta Sync index is created from a Unity Catalog source and kept in step with it: a Delta table, a streaming table, a materialized view, or a managed table using Iceberg v3 or above (create AI Search endpoints and indexes). The source table is the system of record, the index is derived, and the platform keeps the second in step with the first. That synchronisation is the reason we'd use it over a hand-built index, because a hand-maintained index drifts the moment somebody edits a document without rerunning the loader, and stale retrieval is the most dangerous failure mode available. It produces neither an error nor an empty result, but a fluent, confident, correctly formatted answer based on a policy superseded in March, and nobody notices because the answer reads well.
The source doesn't have to be a Delta table written for the index. A streaming table or a materialized view from a Lakeflow pipeline can feed it directly, so the job step that copies pipeline output into a plain chunk table is no longer needed. Where the chunk table is already pipeline output, we'd point the index at it and delete the copy. A materialized view needs external metadata switched on, on the view or on the pipeline that defines it, before it can be a source (enable access for a dataset). Databricks gives no release stage for these sources, so we'd check that page before a production index depends on one.
CREATE OR REPLACE TABLE originations_prd.gold.policy_doc_chunks (
chunk_id STRING COMMENT 'Stable identifier, document id plus ordinal',
document_id STRING COMMENT 'Parent document, used for citation',
section_path STRING COMMENT 'Heading trail, for example Servicing > Arrears > Hardship',
effective_from DATE,
dealer_id STRING COMMENT 'Owning tenant, or GLOBAL when every dealer may read it',
chunk_text STRING
);
ALTER TABLE originations_prd.gold.policy_doc_chunks
SET TBLPROPERTIES (delta.enableChangeDataFeed = true);A standard endpoint needs change data feed on the source table so the sync moves only what changed, which is why the property is set above; a table with row tracking enabled gets it automatically. The index itself is one call.
# %pip install databricks-ai-search
from databricks.ai_search.client import AISearchClient
client = AISearchClient()
client.create_delta_sync_index(
endpoint_name="originations-search",
index_name="originations_prd.gold.policy_doc_index",
source_table_name="originations_prd.gold.policy_doc_chunks",
primary_key="chunk_id",
embedding_source_column="chunk_text",
embedding_model_endpoint_name="databricks-qwen3-embedding-0-6b",
pipeline_type="TRIGGERED",
columns_to_sync=[
"chunk_id",
"document_id",
"section_path",
"effective_from",
"dealer_id",
"chunk_text",
],
)Because the embedding is generated from a column by a named endpoint, the index knows how its own vectors were produced. Two choices come with that call, and we'd make both on purpose:
| Choice | Option | What it gives you | What it costs |
|---|---|---|---|
| Sync | TRIGGERED |
A refresh when the nightly pipeline calls it; incremental on a standard endpoint | Staleness between runs |
| Sync | CONTINUOUS |
Latency in seconds | A streaming pipeline running all the time, so a higher bill |
| Endpoint | Standard | Both sync modes, lowest query latency | More per vector stored |
| Endpoint | Storage optimized | Large corpora, SQL-style filter strings, a keyword-only full-text index (Beta) | Triggered sync only, each sync partly rebuilds the index, and a filtered query can return fewer than k results, even none |
Our default for a policy or documentation corpus is a standard endpoint with triggered sync, kicked off as the last task of the job that writes the chunk table. Continuous sync earns its cost only when a reader would act on a change within minutes, and then we'd usually route that question to SQL against the live table instead (below).
Chunking is where most quality is won or lost #
A chunk is the unit that gets retrieved, so it is also the unit the model has to understand. We'd hold three rules.
Cut on semantic boundaries rather than a fixed character count. Splitting every eight hundred characters will eventually halve a table, separate a heading from the paragraph it governs, and end a chunk mid-sentence. Sections, headings and paragraph boundaries are already present in most documents, and using them costs a little parsing work and returns a great deal of coherence.
Include enough surrounding context that a chunk is interpretable alone. A passage reading "this does not apply where the applicant is a sole trader" is useless without knowing what "this" is, so prepend the document title and the heading trail, and overlap slightly at boundaries.
Carry metadata on every chunk. Document identifier, section path, effective date, source system and owning tenant all belong as columns, because they are what lets you filter before searching, cite afterwards, and exclude a superseded revision without deleting it.
Retrieval is not only vectors #
The word retrieval has become a synonym for semantic search, and treating the two as the same thing is the second most common design mistake here.
Structured retrieval means letting the agent run a governed SQL query against a narrow allow-list of views, usually as a Unity Catalog function or a Genie Agent exposed as a tool. For anything countable it's simply the more correct answer, because "how many applications were declined last month" has an exact answer a warehouse can compute, while semantic search returns three paragraphs that mention declines. Before building a document agent we'd sort the questions people actually ask into countable and not, because a document agent that can't count is usually being asked to count.
Hybrid retrieval runs keyword search alongside vector search and merges the two result lists with reciprocal rank fusion. Pure vector similarity is weak on exact identifiers, product codes, unusual proper nouns and negations, all of which keyword search handles precisely. On AI Search it's one argument, query_type="hybrid", and Databricks now calls it the recommended starting point for most use cases (query an AI Search index). We'd start there too. A hybrid query returns at most 200 results by default, and query_type="FULL_TEXT" (Beta) gives keyword-only search when that's all a question needs.
Reranking takes the candidate set, rescores each candidate against the question with a cross-encoder, and keeps the best few. AI Search has a built-in reranker you pass on the same call. It reads the columns you name in the order you name them and considers only the first 2,000 characters it finds, so put the most telling column first. Databricks puts the gain at about 10 per cent on retrieval quality and the cost at typically under a second per query, and the reranker is a Designated Service, so a workspace outside the US, EU, Australia and New Zealand may need cross-Geo processing enabled before it works:
from databricks.ai_search.reranker import DatabricksReranker
results = index.similarity_search(
query_text=question,
columns=["chunk_id", "document_id", "section_path", "chunk_text"],
query_type="hybrid",
reranker=DatabricksReranker(columns_to_rerank=["section_path", "chunk_text"]),
num_results=5,
)Because that latency lands on every call, we'd add the reranker when the recall measurement below says the right chunk is in the top twenty but not the top five, and not before.
Governed retrieval #
This is the part we won't compromise on. Filter at retrieval time using the identity of the person asking, and never retrieve broadly as a service principal on the understanding that the model will decline to mention what it should not have seen. If the retrieval can see it, treat it as disclosed, because a model instructed to withhold information it has already been given is a request rather than a control, and it fails to a prompt-injected document, a cleverly worded follow-up, or nothing more exotic than the model summarising its sources.
The mechanics are those covered in Multi-Tenant and Per-User Reporting and Unity Catalog, applied one layer up. Entitlements resolve from the caller before the search runs, and become a filter on the index rather than a post-processing step.
def retrieve_policy(question: str, caller: Caller, k: int = 5) -> list[Chunk]:
"""Retrieve policy passages the caller is entitled to read.
Entitlements are resolved from the caller's identity and applied as an
index filter, so unentitled chunks are never returned to the process.
"""
scopes = entitlements.dealer_scopes_for(caller.user_name)
if not scopes:
return []
response = index.similarity_search(
query_text=question,
columns=["chunk_id", "document_id", "section_path", "chunk_text"],
filters={
"dealer_id": scopes + ["GLOBAL"], # tenant documents plus global ones
"effective_from <=": date.today().isoformat(),
},
num_results=k,
)
return [Chunk.from_row(row) for row in response["result"]["data_array"]]Four details there are deliberate. The filter syntax is the standard endpoint's dictionary form, a list meaning "any of" and a key suffix such as <= or NOT for comparisons. A storage-optimized endpoint takes the same filter as a SQL-style string instead ("dealer_id IN ('d-17', 'd-42', 'GLOBAL')"), so the filter builder is endpoint-specific code and belongs under test. Global documents carry an explicit GLOBAL value rather than a null, because the filter docs say nothing about matching nulls and a security filter shouldn't rest on undocumented behaviour. An empty scope set returns nothing rather than falling through to an unfiltered search, because a filter that fails open is worse than no filter at all. The effective date predicate is applied at retrieval rather than left to the model, since a superseded policy in the context window is a superseded policy in the answer.
A worked design: when the table's policies don't reach the index #
Sushruth Aeluguri, a Databricks Engineer at TechFabric, wrote up the sharpest edge of this as a scenario on a FHIR lakehouse design. The structured tables are protected with attribute-based row filters and column masks, so that a care coordinator outside the consented group never sees a substance use record covered by 42 CFR Part 2. Then the agent needs to retrieve from unstructured chart notes. His post describes the table protection as what blocks the index; Databricks' current pages are more precise, and they're what we'd build to. A table-level row filter or column mask stops an AI Search index being created from the table. An ABAC policy does not: the index syncs all rows from the source and "doesn't enforce row filter or column mask policies when serving queries." The only help the platform gives is leaving masked columns out with the columns-to-sync setting. Either way, the table's protection never travels into the index, so the index needs access control of its own.
He sets out three designs and what each costs:
| Design | How it works | What it costs |
|---|---|---|
| Index a de-identified table | De-identify notes during normalization, index the safe copy, one index for everyone | Recall and fidelity, since names and dates sometimes carry the clinical signal, plus a de-identification process whose failures are silent |
| One index per access tier | A non-sensitive index and a restricted one, chosen by the caller's group | Duplicate storage and sync pipelines, drift between tiers, and it stops scaling the day consent becomes per patient |
| Filter after retrieval | Index everything, join retrieved chunk ids back to a governed table, drop what the caller can't see | Embeddings computed over data the caller can't read, unpredictable recall as results drop, and no chunk text may leave the tool before the filter runs |
Whichever design you pick, we'd grant SELECT on each index only to the groups cleared for its tier, never index an ABAC-protected table whole on the assumption that its policies follow, and keep a negative retrieval test in CI: as a caller outside the consented group, search for a phrase that appears only in a restricted note and assert that nothing comes back.
His rule for choosing is the consent model: fixed tiers point at separate indexes, per-patient consent points at de-identification plus a governed structured lookup for anything sensitive. We'd add one thing to the third design from the retrieval code above: if you post-filter, over-fetch (ask for fifty, keep five after the filter), or the filter will quietly return two passages where the model needed five.
Three more points from his write-up bear on retrieval directly, and we'd hold a design review to all of them. The post-filter lives inside the tool function, never in the agent's prompt, because an instruction in a prompt is advice and the function is enforcement. Once retrieval runs on behalf of the user, results are a function of who asked: two coordinators in different consent groups making the identical call get different passages, so a cache of retrieved chunks has to be keyed by identity or not kept at all. And the governed table the post-filter joins should carry the consent decision as a column the pipeline writes, because a filter that joins a consent mapping table runs that lookup per row on every scan:
-- inside the tool function, run as the caller; the row filter on chunks drops what they may not read
SELECT c.chunk_id, c.chunk_text
FROM health.notes.chunks AS c -- ROW FILTER health.gov.part2_visible ON (sensitivity)
WHERE array_contains(:retrieved_ids, c.chunk_id);The count that comes back is the number to log. A tool that asked the index for fifty and got eight after the filter is telling you the over-fetch is too small for that caller, and that's a tuning signal no retrieval metric computed as the service principal will ever show.
What we saw: the parser and the store changed with every client #
Preetham Reddy wrote up why we built Fiber, TechFabric's multi-tenant platform for standing up retrieval-backed copilots. Client corpora ranged from decades of PDFs, spreadsheets and handwritten notes to semi-structured data and relational databases, and each needed a different parsing engine, a different vector store and a different model, so the team kept rebuilding the same pipeline by hand for each client. The fix was to treat ingestion, parsing and embedding as durable Temporal workflows, provisioned per tenant inside the tenant's own cloud, so a component could be swapped when a better one arrived without rebuilding the rest.
The lesson we'd carry to a Databricks build is where to spend the effort. The index is the easy part to choose; the parsing step and the pipeline that keeps embeddings in step with the source are what differ by corpus and what break. On Databricks we'd keep parsing and chunking in a Lakeflow pipeline that writes a governed chunks table, let the index sync from that table, and treat the parser as a replaceable stage with its own evaluation, because the parser that suits scanned forms is rarely the one that suits contracts.
Grounding a model in governed enterprise data
| Capability | Databricks | AWS | Azure | GCP |
|---|---|---|---|---|
| Index kept in sync with the source table | AI Search Delta Sync index from Unity Catalog | Bedrock Knowledge Bases sync from S3, or build it on OpenSearch | AI Search indexers over a data source | Vertex AI Vector Search, build the update path |
| Retrieval under the caller's own entitlements | Grants on the index, plus a filter you resolve from catalog groups; source-table ABAC policies do not apply to the index | Metadata filters you populate and enforce yourself | Security filters you populate and enforce yourself | Filters you populate and enforce yourself |
| Structured retrieval beside text retrieval | Governed SQL over the same catalog | Athena or Redshift, a separate permission model | Synapse or Fabric, a separate permission model | BigQuery, a separate permission model |
| Hybrid keyword and vector | Hybrid search on the index | OpenSearch does this well | AI Search does this well | Combine two services |
| Lineage from source document to answer | Inherited from the catalog | Assemble it | Assemble it | Assemble it |
All four will index your documents competently, and OpenSearch and Azure AI Search are strong retrieval engines we'd happily build on. The difference is that on the other three the index is a separate system with its own copy of the data and its own access model, so the claim that a user only ever retrieves what they may read is something your team builds, tests and defends. On Databricks the index derives from a governed table and its grants live in the same catalog as the data, which makes most of that claim configuration. Most, because the source table's ABAC policies don't follow it into the index, so the per-caller filter and a negative retrieval test are still yours to build.
Advanced: the parts teams reach later #
Compaction and summarising history. A long conversation eventually exceeds the budget, and the usual answer is to summarise older turns into a compact note. Specifics are what that costs, because numbers, identifiers, exact quotes and the precise wording of a constraint are the first things summarisation discards, so a compacted conversation keeps the gist of what the customer wanted and loses the account number they gave you eleven turns ago. Keep structured facts in a slot that is never summarised, and compact only the prose.
Caching. Prompt caching stores the processed form of a prefix so that repeated calls sharing it skip most of the work, cutting both cost and time to first token on workloads with a large fixed preamble. Prefix order therefore matters, so put the stable material first, meaning system instructions, tool definitions and fixed reference text. Anything that changes invalidates the cache from that point onwards, which is why interleaving a timestamp or the user's name into the system prompt quietly costs more than it looks.
Metadata as retrieval context. An agent chooses a table by reading its table and column descriptions, so a well described schema is retrieval input as well as documentation. This is the argument the semantics pillar makes in Reporting, Semantics, and Power BI. Unity Catalog semantics gives metric views a governed home, and a Genie Agent's knowledge store holds column synonyms, sampled values, join relationships and SQL expressions for one subject area. Both are context the model reads, and both improve answers without touching the model.
Evaluate retrieval separately from generation. When a system answers wrongly you need to know whether the passages were wrong or the reasoning was, and an end-to-end score can't tell you. We'd build a labelled set naming, for each question, which chunk identifiers contain the answer, then measure recall at k, the share of questions where a correct chunk appears in the top k results. It's a few lines against the index:
def recall_at_k(index, labelled: list[dict], k: int = 5) -> float:
hits = 0
for row in labelled: # {"question": ..., "chunk_ids": {...}}
got = index.similarity_search(
query_text=row["question"], columns=["chunk_id"], num_results=k, query_type="hybrid"
)["result"]["data_array"]
hits += any(r[0] in row["chunk_ids"] for r in got)
return hits / len(labelled)If recall at five is sixty per cent, no amount of prompt engineering will fix the system, and the next change belongs in chunking or hybrid search. AI Search also has a built-in retrieval quality evaluation that compares query types on your index, which is worth running once beside your own labelled set. We'd log this number as an MLflow metric on every change to the chunker so the argument about chunk size has a history.
Freshness and the window in between. Between a source table changing and the index reflecting it there is a gap, measured in minutes for continuous sync and in however often you trigger it otherwise. For a policy corpus that gap is harmless. For pricing, inventory, entitlements or anything a customer will act on it is a correctness problem, and the answer is usually to route those questions to structured retrieval against the live table rather than to make the index faster.
Long documents and multimodal content. Some material resists chunking, including contracts where a clause depends on definitions forty pages earlier and scanned documents where the meaning sits in a diagram. Here a larger context window genuinely is the right answer rather than a way of avoiding retrieval work, and the pattern that works is two-stage, where retrieval identifies the relevant document and the whole document then goes to a long-context model.
The order we'd tune retrieval in #
When answers disappoint, teams reach for the change that's easiest to make, which is usually the model or the result count. We'd work in a fixed order instead, because each step is cheaper than the next and each one changes what the next measurement means.
| Step | What we'd change | The measurement that says it worked | Why it comes here |
|---|---|---|---|
| 1 | Write 50 to 100 labelled questions with the chunk ids that answer them | Recall at 5 exists at all | Every later step is an argument without it |
| 2 | Route countable questions to governed SQL | Those questions leave the retrieval set and get exact answers | The cheapest accuracy gain there is |
| 3 | Re-chunk on headings with the heading trail prepended | Recall at 5 rises | Retrieval can't find what chunking broke |
| 4 | Confirm hybrid search is on, or switch to it | Recall rises on questions containing ids and codes | One argument, no new infrastructure |
| 5 | Add the reranker | The right chunk moves from the top 20 into the top 5 | Costs latency on every call, so it waits for evidence |
| 6 | Tune the result count down | Answer quality holds or rises with fewer passages | Fewer tokens on every call, for the life of the feature |
| 7 | Change the model | Generation scores rise with retrieval held fixed | Last, because it's the most expensive change to evaluate |
The table is our position, worked out from how the pieces depend on each other rather than from a benchmark: a better model can't rescue a chunk that never reached it, and a reranker can't promote a passage that recall never fetched.
What we would tell a team starting today #
We'd write the labelled retrieval set before building the pipeline, because it converts every later argument about chunk size into a measurement. Chunk on structure, carry metadata, and resist raising the result count when quality disappoints, since the fix is almost always a better candidate set rather than a bigger one. Put the entitlement filter in on the first day, because retrofitting it means auditing every call site. What to do with a well-grounded model is Agents on Databricks.
What's popular