CertSafari
    Databricks Certified Generative AI Engineer Associate· Lessons

    Domain 2 · Lesson 13/56

    Context-enriched chunks and ai_prep_search

    Design retrieval systems using advanced chunking strategies

    11 min read
    1.75% of exam
    2 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Add the document title, section and summary to chunks, or store them as separate metadata columns, and know what each choice needs downstream
    • Call ai_prep_search on ai_parse_document output or on plain text, with and without a metadata schema
    • Tell chunk_to_embed from chunk_to_retrieve, and flatten the output into rows for an AI Search index

    1.Making a chunk meaningful on its own

    A chunk cut out of a document loses its surroundings. Take a paragraph about adjustment steps from a brake-maintenance manual. On its own it never says that it is about brakes, which manual it comes from, or which procedure it belongs to. A query such as 'emergency brake adjustment' may then miss it. Context enrichment puts that missing information back by attaching document-level context to every chunk.

    The simplest approach writes the context straight into the chunk text, so the embedding model reads it along with the content. The extra context gives embedding models more semantic signal, gives rerankers more to score with, and helps with queries that refer to document-level ideas the chunk text never mentions.

    Prepending document title, summary and section name to every chunkpython
    # Prepend document summary to each chunk
    chunk_with_context = f"""
    Document: {doc_title}
    Summary: {doc_summary}
    Section: {section_name}
    {chunk_content}
    """

    The alternative is to store the same information as separate metadata columns, such as doc_summary, section and keywords, and leave the chunk text alone. Those columns do nothing for the vector match by themselves. Semantic metadata needs a reranker configured to read it through the columns_to_rerank parameter, which is covered in the role of re-ranking. Keyword-only metadata needs hybrid search in full-text mode to match against those fields. Prepending works with any downstream setup. Separate columns keep the embedded text cleaner, but only pay off if you configure that extra processing.

    Checkpoint 1 of 5· Check yourself

    A team indexes a brake-maintenance manual. They store doc_summary and section as separate metadata columns and leave the chunk text unchanged. Retrieval uses plain vector similarity search. Queries for 'emergency brake adjustment' still miss the adjustment-step chunks. What explains this, and what fixes it?

    Sources1

    2.ai_prep_search: chunking and enrichment in one SQL call

    ai_prep_search is a Databricks SQL function, currently in Beta, that does chunking and context enrichment in one call. For each input document it splits the content into semantic chunks, adds document-level context to each chunk (title, section headers, page references) and produces text ready for embedding. It needs Databricks Runtime 18.2 or above. On serverless compute it also needs environment version 3 or above, because that version enables VARIANT. It runs from notebooks, the SQL editor, workflows, jobs and Lakeflow pipelines.

    The first argument accepts two kinds of input. A VARIANT should be the structured output of ai_parse_document, which is the richest input because it keeps page headers, captions and tables. Other VARIANT data, or an unsupported schema version, can give unexpected results or errors. A STRING should be plain text or Markdown. A JSON string that is not parse output is not rejected; it is indexed as literal text. The optional options map supports two keys: version, which pins the output schema version, and schema, which lists the document-level metadata fields to extract.

    Chaining ai_parse_document into ai_prep_search over files in a Unity Catalog volumesql
    WITH parsed_documents AS (
      SELECT ai_parse_document(content) AS parsed
      FROM READ_FILES('/Volumes/mydata/documents/', format => 'binaryFile')
    )
    SELECT ai_prep_search(parsed) AS result
    FROM parsed_documents;

    The schema option controls which metadata fields are extracted. Without it, an LLM picks field names for each document, such as Company, Document Type or Fiscal Year, so different documents can end up with different keys. A simple schema is a JSON array of field names, all treated as strings: '["company", "document_type", "fiscal_year"]'. An advanced schema is a JSON object that adds types (string, integer, number, boolean, enum), descriptions that guide extraction, and nested objects or arrays. Its values are type-validated, and a value that fails validation raises an error. Use a schema whenever you plan to filter on a field, because filters need the same key in every document.

    Checkpoint 2 of 5· Fill the gap

    This pipeline reads raw PDFs from a Unity Catalog volume and prepares them for vector search. Which function belongs in the blank so that ai_prep_search gets its richest input, with page headers, captions and tables kept?

    WITH parsed_documents AS (
      SELECT  ? (content) AS parsed
      FROM READ_FILES('/Volumes/mydata/documents/', format => 'binaryFile')
    )
    SELECT ai_prep_search(parsed) AS result
    FROM parsed_documents;

    Checkpoint 3 of 5· Check yourself

    Chunks produced by ai_prep_search are indexed with no options set. A filter on fiscal_year now misses many documents. Their chunks show the year under keys such as 'Fiscal Year' or 'Year'. What is the cause, and what fixes it?

    Sources2

    3.chunk_to_embed versus chunk_to_retrieve

    The two fields split the work between matching and answering. chunk_to_retrieve is the raw chunk text. chunk_to_embed wraps that same text in context. It starts with fixed labelled lines (Document Title, Page Header, Page Footer, Section Header, Caption, Footnote, Page Number). Next come the document fields as Key: Value lines, then a one-sentence summary of the document written by an LLM, then the content itself. Chunks that contain a table also get a short summary of the table and a list of natural-language questions the table can answer, which improves recall for tabular data.

    A rendered chunk_to_embed: empty fixed fields keep their labels, and the raw chunk follows Content:text
    Document Title: Acme Corp 2024 Annual Report
    Page Header:
    Page Footer:
    Section Header: Risk Factors
    Caption:
    Footnote:
    Page Number: 14
    Company: Acme Corp
    Document Type: 10-K
    Fiscal Year: 2024
    
    Acme Corp's 2024 annual report covering financial performance and risk disclosures across global operating segments.
    
    Content:
    Our business faces a number of risks, including competition from established providers, evolving regulatory requirements, and concentration in a small number of large customers.

    The two kinds of field behave differently when a value is missing. The fixed fields always appear with their label, even when the value is empty, as Page Header does above. The document fields, the summary sentence, the table summary and the related questions are left out completely when they don't apply. This chunk has no table, so it has no table summary and no related questions. The exact layout is versioned and may change, so pin version in options if downstream code parses this string.

    Checkpoint 4 of 5· Match them up

    An ai_prep_search output row is being mapped into an AI Search index and a prompt builder. Match each part of the output to how it behaves or what it is used for.

    Tap a term, then the definition that fits it.

    Sources2

    4.Flattening the output into index-ready rows

    ai_prep_search returns one row per input document, with all of that document's chunks inside result:document.contents. An AI Search index needs one row per chunk. LATERAL variant_explode(prepped_documents.result:document.contents) expands the array, and casts such as chunk.value:chunk_to_embed::STRING turn each field into a typed column. You can write the result to a Delta table and use that table as the index's source. Fields named in the schema option can be pulled out as their own columns in the same way, for example chunk.value:metadata:fiscal_year::INT, so they can be used as filters.

    Columns of the flattened ai_prep_search table and their role in the index
    ColumnTypeRole
    chunk_idSTRINGPrimary key; document ID combined with chunk position
    chunk_positionINT0-based position of the chunk within its document
    chunk_to_retrieveSTRINGRaw chunk text to pass to the LLM
    chunk_to_embedSTRINGContext-enriched text; the embedding column
    metadataVARIANTTyped values for the schema keys; empty object when schema is omitted
    source_uriSTRINGPath of the source document

    Each chunk also has a pages array that lists the pages it appears on. If ai_parse_document was called with imageOutputPath, the rendered page images are saved to a Unity Catalog volume, and each page entry gets an image_uri. At query time you can pass those images to a vision-capable model to answer questions about diagrams, charts or tables that the text alone does not fully capture.

    Checkpoint 5 of 5· Check yourself

    After running ai_prep_search over a folder of PDFs, an engineer writes ai_prep_search(parsed) AS result straight into a Delta table and tries to use that table as an AI Search source. The table has one row per PDF. What should they do to get index-ready rows?

    Sources2

    Practise it for real

    Turn a volume of raw documents into chunk rows you can use as the source for an AI Search index, using ai_prep_search

    1. 1.Run SELECT ai_prep_search('Quarterly revenue grew twenty percent year over year.', options => map('version', '2.0')); on Databricks Runtime 18.2 or above.

      Why: This confirms the function is available on your compute and shows the output shape for a plain STRING input.

      You should see: One VARIANT row with document.contents holding a single chunk that has chunk_id, chunk_to_retrieve and chunk_to_embed.

    2. 2.Chain ai_parse_document over READ_FILES on a volume of PDFs into ai_prep_search(parsed).

      Why: Parsed VARIANT input lets the function fill in Document Title, Section Header and Page Number from the document's real structure.

      You should see: One result row per document, each holding several chunks in document.contents.

    3. 3.Add map('schema', '["company", "document_type", "fiscal_year"]') as the options argument.

      Why: A fixed schema gives every chunk the same metadata keys, which you need for filtering.

      You should see: Each chunk's metadata object and chunk_to_embed contain those three keys.

    4. 4.Flatten with LATERAL variant_explode(prepped_documents.result:document.contents), selecting chunk_id, chunk_to_retrieve and chunk_to_embed as typed columns.

      Why: An index needs one row per chunk, not one row per document.

      You should see: One row per chunk, ready to write to a Delta table with chunk_id as primary key and chunk_to_embed as the embedding column.

    Stuck? Get a nudge

    Compare chunk_to_embed and chunk_to_retrieve for the same row. The text after Content: should be exactly the chunk_to_retrieve value.

    Sources

    (2)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “Provides additional semantic signal for embedding models.”
      ↩︎ Making a chunk meaningful on its own
      “For keyword-only metadata: Use hybrid search (full-text mode) to match against these fields.”
      ↩︎ Making a chunk meaningful on its own
      “This approach requires downstream processing to leverage the metadata:”
      ↩︎ Exam trap 1
      “For semantic metadata: Use reranking with columns_to_rerank parameter to consider these columns.”
      ↩︎ Checkpoint
    2. 2.
      “splits content into semantic chunks, enriches each chunk with document-level context such as the document title, section headers, page references”
      ↩︎ ai_prep_search: chunking and enrichment in one SQL call
      “Without the schema option, an LLM discovers field names per document”
      ↩︎ ai_prep_search: chunking and enrichment in one SQL call
      “The fixed metadata fields are always rendered with their label, with the value left empty when not available.”
      ↩︎ chunk_to_embed versus chunk_to_retrieve
      “using chunk_to_embed as the embedding column and chunk_id as the primary key.”
      ↩︎ Flattening the output into index-ready rows
      “JSON strings that are not structured parse-document output are indexed as literal text rather than rejected.”
      ↩︎ Exam trap 2
      “using chunk_to_embed as the embedding column and chunk_id as the primary key.”
      ↩︎ Prediction
      “A VARIANT containing document chunks formatted for vector search indexing. Each row in the output represents one input document.”
      ↩︎ Checkpoint

    Ready to test yourself?

    Practise the 6 questions on this subdomain.

    Spotted a mistake, or was something unclear? Tell us.