Home / GenAI Engineer practice test / Data Preparation

Free · 8 questions with explanations

Data Preparation: Databricks Generative AI Engineer Associate Practice Questions

Exam-style questions on Data Preparation. Pick your answer, then open the explanation to see why it's right — and why the other options are wrong.

1 Data Preparation

A generative AI engineer is building a product FAQ chatbot. The source data is a structured FAQ document with 350 question-answer pairs in the format: **Q:** [question text] **A:** [answer text]. Each QA pair is 2–8 sentences on average. Users will query the chatbot with questions semantically similar to the FAQ questions. The engineer is choosing between three chunking strategies. Which approach produces the BEST retrieval quality for this specific document structure?

  1. ARecursive character text splitting with 512-token chunks and 50-token overlap, using default whitespace separators. This is universally the best chunking strategy for any document type and requires no document-specific configuration.
  2. BOne-chunk-per-QA-pair splitting — each complete Q+A pair is one chunk. This preserves the semantic unit of the FAQ (the question fully contextualizes the answer), ensures the retrieved chunk always contains the answer to a similar question, and aligns the chunk's semantic content with the query type (questions).
  3. CSplit questions and answers into separate chunks — index the question text and answer text as independent chunks. This doubles the index density and increases the probability that either the question or answer embedding matches the user's query.
  4. DFixed-size 128-token chunks with no overlap. FAQ answers are short, so 128 tokens is sufficient. Small chunks improve retrieval recall by creating more fine-grained index entries.
  5. ESentence-level chunking across the entire FAQ document, treating sentence boundaries as chunk boundaries while ignoring Q/A structure. Since FAQ answers are factual sentences, sentence-level granularity maximizes retrieval precision.
Show answer & explanation

Correct answer: B

WHY B is correct: When source documents have a natural semantic unit — in this case, the Q+A pair — the chunking strategy should preserve that unit. A document with explicit Q/A structure provides a strong signal: each QA pair is a self-contained knowledge nugget. When a user asks a question similar to a FAQ question, embedding-based retrieval will score the chunk highest when the chunk contains the FAQ question + answer as a complete unit, because the FAQ question and the user query will be semantically close, and the complete answer is co-located. Splitting per-QA-pair is sometimes called 'structure-aware' or 'document-aware' chunking. WHY NOT A: Recursive character splitting ignores the QA structure and may split a QA pair mid-answer or merge partial answers from two adjacent QA pairs into one chunk. A generic strategy that ignores document structure always underperforms a structure-aware strategy when clear semantic units exist. WHY NOT C: Separating the question from its answer into different chunks breaks the retrieval-answer co-location property. If a user query retrieves the FAQ question chunk (high similarity, since both are questions), the retrieved chunk contains no answer text — the LLM must then try to answer without any retrieved context. If the answer chunk is retrieved (lower similarity, since answer text is often declarative while queries are interrogative), it lacks the question's framing. WHY NOT D: Fixed 128-token chunks cut some QA pairs mid-answer (an 8-sentence answer may exceed 128 tokens), again breaking the semantic unit. Small chunks also create more noise in the index by splitting structural units that should stay together. WHY NOT E: Sentence-level chunking across the entire document obliterates the QA structure. A retrieved single sentence like 'The return window is 30 days' has almost no context about what product, what conditions, or what exceptions apply. The user would receive ambiguous, context-free fragments instead of complete answers.

2 Data Preparation

A generative AI engineer is designing a high-quality RAG pipeline for a medical knowledge base. The current pipeline retrieves top-5 chunks using a bi-encoder with cosine similarity. The engineer wants to add a re-ranking stage using sentence_transformers.CrossEncoder. Which statement correctly describes a key LIMITATION of cross-encoder re-ranking that the engineer must account for when designing the system?

  1. ACross-encoders can only be used with documents shorter than 128 tokens. Any retrieved chunk longer than 128 tokens must be truncated before re-ranking, which causes information loss.
  2. BCross-encoders require the query and chunk to be in the same language. Multilingual documents cannot be re-ranked by any cross-encoder model.
  3. CCross-encoders cannot produce document embedding vectors and therefore cannot be used to pre-index documents. A cross-encoder must score every (query, candidate_chunk) pair at query time, making them computationally impractical for re-ranking the full document index. They are practical only as a second-stage re-ranker applied to a small candidate set (typically 20–100 chunks) pre-selected by a fast first-stage bi-encoder.
  4. DCross-encoder re-ranking always increases final answer accuracy in RAG applications, regardless of the quality of the initial bi-encoder retrieval. Adding a re-ranker is risk-free because it can only maintain or improve precision over the bi-encoder baseline.
  5. ECross-encoders are only available as proprietary cloud API services. Open-source cross-encoder models do not exist, and calling a cloud re-ranking API introduces mandatory data privacy risks incompatible with medical applications.
Show answer & explanation

Correct answer: C

WHY C is correct: This is the fundamental, well-documented limitation of cross-encoders. A cross-encoder scores a (query, document) pair by running a full transformer forward pass on both texts simultaneously. This requires one separate forward pass per candidate document. For a corpus of 1 million chunks: - **ANN (Approximate Nearest Neighbor) bi-encoder search**: ~5–50 milliseconds (pre-computed embeddings + vector index) - **Cross-encoder scoring 1M chunks**: 1M × ~5ms per pair = ~1,400 hours per query This makes cross-encoders completely impractical as a first-stage retriever over large indices. They are practical ONLY as second-stage re-rankers applied to a small set of candidates (20–100) pre-selected by the bi-encoder. This two-stage architecture is the canonical 'retrieve-then-rerank' pipeline, and the sentence_transformers documentation explicitly frames CrossEncoder usage this way. WHY NOT A: Cross-encoder context window limits depend on the underlying model, typically 512 tokens for BERT-based models or 4,096+ tokens for modern transformer architectures. The limit is not universally 128 tokens, and truncation behavior is configurable. The 128-token claim is false. WHY NOT B: Multilingual cross-encoder models exist (e.g., cross-encoder/mmarco-mMiniLMv2-L12-H384-v1 from the sentence_transformers library). The claim that cross-encoders require same-language query and document is false — it depends on the model trained. WHY NOT D: Cross-encoder re-ranking can only re-rank candidates within the set retrieved by the first-stage bi-encoder. If the relevant chunk was not in the top-K bi-encoder results (recall failure), the cross-encoder cannot elevate it because it never sees it. The cross-encoder is bounded by the recall ceiling of the first stage. Additionally, if the cross-encoder model is poorly calibrated or mismatched to the domain, re-ranking can decrease precision. WHY NOT E: Multiple open-source cross-encoder models are available from Hugging Face Model Hub via the sentence_transformers library (e.g., cross-encoder/ms-marco-MiniLM-L-6-v2, cross-encoder/ms-marco-TinyBERT-L-2-v2). These can run entirely on-premises without any cloud API call. The claim that only proprietary cloud APIs exist is false.

3 Data Preparation

A generative AI engineer is building a RAG application that ingests four types of source documents: (1) native digital PDFs with text layers (financial reports), (2) scanned image-based PDFs with no text layer (legacy paper contracts that were photocopied and scanned), (3) HTML web pages from an internal wiki, and (4) .docx Word documents. The engineer needs to extract the text content from all four types using Python. Which library combination CORRECTLY handles all four source types?

  1. AUse PyPDF2 for all four types. PyPDF2 can extract text from any PDF file format and also has built-in support for HTML and DOCX parsing through its universal document reader interface.
  2. BUse pdfminer.six for digital PDFs, pytesseract (with Pillow for image rendering) for scanned image PDFs, BeautifulSoup for HTML pages, and python-docx for DOCX files.
  3. CUse pypdf for digital PDFs, pytesseract (with pdf2image to convert PDF pages to images first) for scanned image PDFs, BeautifulSoup for HTML pages, and python-docx for DOCX files.
  4. DUse scrapy for all web-accessible content and textract for PDFs and DOCX. Scrapy's built-in document parser supports PDFs, DOCX, and HTML from any URL. textract handles binary documents that Scrapy cannot reach.
  5. EUse the unstructured library for all four types. The unstructured library provides a single unified partition() function that detects file type and routes to the correct internal parser — including OCR for image-based PDFs, HTML parsing, and DOCX text extraction — without requiring separate package selection per format.
Show answer & explanation

Correct answer: E

WHY E is correct: The unstructured library (by Unstructured.io) is specifically designed for this multi-format document extraction use case. Its partition() function automatically detects the file type (PDF, DOCX, HTML, image) and routes to the appropriate internal parser. Critically for scanned PDFs with no text layer, unstructured integrates with Tesseract OCR via the unstructured[local-inference] install and applies OCR automatically when it detects a PDF with no extractable text layer. This means a single consistent API call handles all four source types without branching logic per format — which is the minimal-engineering approach favored in production RAG pipelines on Databricks. WHY NOT A: PyPDF2 (now pypdf) works ONLY for digital PDFs with embedded text layers. It has no HTML parser, no DOCX parser, and no OCR capability. Attempting to extract text from a scanned image PDF with PyPDF2 returns empty strings because there is no text layer — it extracts nothing. The claim of a 'universal document reader interface' is false. WHY NOT B and C: These combinations are technically correct and would work, but they require separate library calls per document type. Options B and C both correctly identify pytesseract + image rendering for scanned PDFs, BeautifulSoup for HTML, and python-docx for DOCX. However, answer E (unstructured) provides a single unified API that handles all four types with type auto-detection, making it the more practical and maintainable choice in production. Both B and C are not wrong per se, but E is more correct as the optimal answer for a production system. WHY NOT D: scrapy is a web crawling framework for extracting content from websites via HTTP requests — it does not parse local PDF or DOCX binary files. textract is a wrapper library that calls external system utilities (pdftotext, antiword, etc.), which must be separately installed at the system level and are not always available in cloud notebook environments. textract also does not support OCR for image-based PDFs without additional configuration.

4 Data Preparation

A generative AI engineer is designing a RAG system for a large collection of academic research papers. Each paper has an abstract, 4-8 sections with subsection headings, and a references section. User queries vary from 'What does the abstract of the Smith 2023 paper say about climate sensitivity?' to 'How do recent papers frame the debate between solar forcing and greenhouse gas causation?' The engineer wants to enable both precise abstract-level retrieval and broad conceptual cross-paper retrieval in a single system. Which retrieval system design BEST supports this?

  1. ACreate separate fixed-size 512-token chunks for all sections uniformly. Structured documents like research papers do not benefit from structure-aware chunking because academic prose is semantically dense throughout.
  2. BUse a metadata-enriched chunking strategy combined with semantic chunking: (1) extract each paper's abstract as a dedicated chunk with metadata {'section': 'abstract', 'paper_id': ..., 'year': ..., 'authors': ...}, (2) split body sections using semantic boundaries (paragraph-level) with section metadata, (3) at retrieval time, use metadata filtering to restrict search to 'abstract' chunks for abstract-specific queries and use full index search for broad conceptual queries. This leverages document structure as retrieval filters.
  3. CUse proposition-based chunking: decompose every sentence in every paper into atomic, self-contained factual propositions using an LLM (e.g., 'The study found a climate sensitivity of 3.1°C per doubling of CO2'). Index each proposition as a separate chunk. All query types benefit from maximally granular retrieval units.
  4. DIndex only the abstract section of each paper and discard the body sections. Research papers are designed so that the abstract contains all information sufficient to answer any question about the paper's content.
  5. EUse random 200-token subsampling: randomly select 200-token windows from each paper and index only those. Random sampling ensures equal coverage of all paper sections without structural bias.
Show answer & explanation

Correct answer: B

WHY B is correct: Metadata-enriched chunking with semantic boundaries combines two powerful techniques for academic paper retrieval: 1. **Section-aware metadata**: Tagging each chunk with section: 'abstract', paper_id, year, authors enables metadata filtering at retrieval time. For the query 'What does the abstract of the Smith 2023 paper say?', the retriever can filter WHERE section = 'abstract' AND authors CONTAINS 'Smith' AND year = 2023 before performing similarity search — dramatically reducing search space and improving precision. 2. **Semantic boundaries**: Splitting body sections at paragraph boundaries (semantic chunking) rather than arbitrary token positions preserves the coherent argument structure of academic paragraphs, improving embedding quality. 3. **Dual query support**: For broad conceptual queries ('debate between solar forcing and greenhouse gas causation'), full index search (no metadata filter) retrieves the most semantically relevant paragraphs from across all papers. WHY NOT A: Uniform 512-token fixed-size chunks ignore the structural signal that 'abstract' sections provide. A query specifically asking about an abstract will retrieve any chunk, not necessarily the abstract section. Structured documents with distinct section types always benefit from structure-aware chunking. WHY NOT C: Proposition-based chunking decomposes content into atomic factual claims and is an advanced strategy that works well for dense factual retrieval. However, it requires running an LLM over every sentence of every paper (computationally expensive for a large academic corpus), and propositions lose the relational context between claims within a paragraph — relevant for synthesis queries about debates and frameworks. WHY NOT D: Indexing only abstracts discards 90%+ of each paper's informational content. The body sections contain methodology, experimental results, and discussion of debates that are essential for synthesis questions. An abstract-only index cannot answer 'How do recent papers frame the debate between X and Y?' because the framing of the debate is in the discussion sections, not the abstract summaries. WHY NOT E: Random subsampling introduces arbitrary coverage gaps. Some critical sections may be underrepresented or absent from the sample. There is no principled way to ensure that specific sections (abstracts, conclusions) or specific arguments are consistently represented. This is an anti-pattern that trades a solvable structural chunking problem for non-deterministic coverage quality.

5 Data Preparation

A generative AI engineer has built a retrieval system for a RAG application and wants to evaluate its performance. They have a golden evaluation dataset of 150 question/answer pairs, where each pair includes: the question, the ground-truth answer, and the list of source document chunk IDs that contain the information needed to answer the question. The retrieval system returns the top-5 chunk IDs for each query. Which pair of metrics is MOST appropriate to evaluate retrieval quality using this evaluation dataset?

  1. ABLEU score and ROUGE-L. BLEU measures the n-gram precision overlap between the retrieved chunk text and the ground-truth answer text. ROUGE-L measures the longest common subsequence. Together they evaluate whether retrieved content lexically matches the expected answer.
  2. BRecall@K and Precision@K (or Mean Reciprocal Rank). Recall@K measures the fraction of ground-truth relevant chunks that appear in the top-K retrieved results. Precision@K measures the fraction of top-K retrieved results that are actually relevant. MRR measures how highly the first relevant result is ranked. These metrics directly assess whether retrieval returns the correct source chunks.
  3. CPerplexity and cross-entropy loss. Lower perplexity in the retrieved chunks indicates they are more fluent text, which correlates with higher quality retrieval results that the LLM can better utilize.
  4. DLatency (milliseconds per query) and index storage size (GB). Operational performance metrics are the primary evaluation criteria because a high-quality but slow retrieval system is not production-viable.
  5. EAnswer correctness and faithfulness (using an LLM-as-judge). An LLM judge can evaluate whether the final generated answers are correct and grounded — because answer quality is the ultimate measure of RAG performance, end-to-end quality metrics are more informative than retrieval-only metrics.
Show answer & explanation

Correct answer: B

WHY B is correct: The question specifically asks to evaluate *retrieval* performance using a dataset that includes ground-truth chunk IDs. Recall@K, Precision@K, and Mean Reciprocal Rank (MRR) are purpose-built information retrieval metrics that measure whether the retriever returns the correct chunks: - **Recall@K**: what fraction of the relevant chunks appear in the top K retrieved? (Catches whether the retriever finds all needed information) - **Precision@K**: what fraction of the K retrieved chunks are actually relevant? (Measures retrieval noise) - **MRR**: where does the first relevant chunk appear in the ranked list? (Measures ranking quality) With ground-truth chunk IDs available, these metrics can be computed directly and faithfully. WHY NOT A: BLEU and ROUGE-L measure lexical overlap between output text strings — they are generation quality metrics used to evaluate summarization and translation outputs. They cannot be directly applied to compare chunk IDs or rank positions, and they measure surface text similarity rather than retrieval recall/precision. WHY NOT C: Perplexity measures a language model's uncertainty in predicting a text sequence — it is a training metric for language models, not a retrieval quality metric. Low perplexity means text is predictable/fluent, not that the chunk is relevant to the user's question. A fluent but irrelevant chunk would have low perplexity and incorrectly score as a high-quality retrieval. WHY NOT D: Latency and storage are operational/infrastructure metrics, not retrieval quality metrics. A fast retriever that returns wrong chunks scores perfectly on latency but fails completely on the task. These metrics are important in production profiling but do not measure retrieval effectiveness. WHY NOT E: Answer correctness and faithfulness (LLM-as-judge end-to-end metrics) evaluate the full RAG pipeline including the generation step. While ultimately important, they conflate retrieval quality with generation quality — a poor-quality retriever can sometimes be masked by a powerful enough LLM. To specifically diagnose retrieval problems, isolated retrieval metrics (Recall@K, Precision@K) are needed.

6 Data Preparation

A generative AI engineer is building a technical documentation chatbot for a software product. The documentation corpus includes 1,200 Markdown files. After building the initial RAG pipeline, retrieval quality evaluations show poor results for questions about API endpoints. Investigation reveals that retrieved chunks frequently contain only code block content without any surrounding explanatory text, and these code-only chunks push out substantive explanation chunks from the top-k results. Additionally, some retrieved chunks contain only a list of hyperlinks (the Markdown 'See also' sections). Which TWO pre-processing filters most directly address these quality degradation sources?

  1. ARemove all code blocks entirely from all documents and index only the prose explanation text.
  2. BFilter out chunks that, after extraction, consist of more than 70% code tokens with less than 30 words of natural language text. These 'code-only' chunks lack explanation context and harm dense vector retrieval quality.
  3. CRemove the Markdown 'See also' and 'References' link sections using a regex pattern that identifies consecutive lines consisting solely of Markdown hyperlinks ([text](url)). These sections contain no substantive informational content.
  4. DConvert all Markdown files to plain text by stripping all formatting symbols before extraction. Markdown symbols (#, **, -) confuse the embedding model and introduce noise into the vector representations.
  5. EIncrease the number of retrieved chunks from top-3 to top-10. More retrieved chunks increase the probability that at least one substantive explanation chunk appears in the context, outweighing the code-only and link-only chunks.
Show answer & explanation

Correct answer: BC

WHY B and C are correct: These two filters directly address the two identified quality degradation sources. (B) Code-only chunk filtering: Dense vector search uses cosine similarity on semantic embeddings. Code blocks produce embeddings heavily influenced by programming language tokens, identifiers, and syntax — not semantic meaning in the domain question space. When users ask 'How do I authenticate to the API?', a code-only chunk embedding for import requests; response = requests.get(url, headers=auth_header) will score lower than a prose explanation chunk but still occupies a top-k slot, displacing better context. Setting a minimum prose token threshold (e.g., >30 words of natural language required per chunk) filters these low-utility code-only chunks. Code can still appear in chunks alongside explanatory text. (C) Link section removal: 'See also' sections with only Markdown hyperlinks have zero retrievable text content — the URL paths and display text ('See UserAuthentication docs') are semantically noisy and not answerable knowledge. They function as navigation aids, not informational content, and should be stripped before chunking. WHY NOT A: Removing all code blocks is an over-aggressive filter. Documentation quality for technical questions often relies on seeing code examples alongside explanations. The problem is code-only chunks with no prose context — not code appearing within chunks that also contain explanation text. WHY NOT D: Stripping Markdown formatting symbols is a common pre-processing step (recommended for cleaner tokenization), but it does not address the two specific problems: code-only chunks still exist as code-only chunks after stripping # symbols, and link sections still exist as a list of URL paths. WHY NOT E: Increasing top-k from 3 to 10 is a mitigation, not a fix. It increases context window usage (potentially hitting the LLM's context limit), adds latency, and introduces more potentially irrelevant content — all making the generation step harder, not easier. The root cause (low-quality index entries) must be addressed at the data preparation stage.

7 Data Preparation

A generative AI engineer is building a RAG system for a 500-page technical specification document. Users ask two types of questions: (1) detail-oriented lookup questions like 'What is the maximum packet size defined in Section 3.4.2?' — requiring a small, precise chunk, and (2) broad synthesis questions like 'How does the error handling strategy in the network layer relate to the application layer?' — requiring large sections of multi-section context. With a standard fixed-size 256-token chunking strategy, detail queries work well but synthesis queries fail because each chunk only captures a small portion of a large multi-section topic. Which advanced chunking strategy BEST addresses the dual query type requirement?

  1. AIncrease chunk size to 4,096 tokens uniformly. Larger chunks always improve synthesis query quality. For detail queries, the LLM can extract the specific value it needs from larger chunks.
  2. BParent-child (small-to-big) chunking: create small child chunks (e.g., 128 tokens) for embedding and retrieval. Each child chunk has a pointer to its parent large chunk (e.g., 1,024 tokens covering the full section). Retrieve using child chunk similarity, but return the parent chunk as context to the LLM. This gives retrieval precision of small chunks while providing broader synthesis context to the generation step.
  3. CSentence Window Retrieval: Index individual sentences as chunks. When a sentence is retrieved, expand the context window by including the N sentences before and after it in the returned context. This provides local context for detail questions while allowing some cross-sentence synthesis.
  4. DStore the entire document as a single chunk and rely on the LLM's long context window (e.g., 128K tokens) to handle both detail and synthesis queries. Full document context eliminates the need for retrieval altogether.
  5. EUse keywords-only BM25 retrieval instead of dense vector retrieval. BM25 retrieves documents based on exact keyword matches, which is more precise for detail queries (exact technical terms) and more comprehensive for synthesis queries (documents containing many topic-related terms).
Show answer & explanation

Correct answer: B

WHY B is correct: Parent-child (also called 'small-to-big' or 'hierarchical') chunking is the advanced strategy specifically designed to serve dual granularity requirements. The architecture is: 1. **Indexing**: Chunk the document into small child chunks (128 tokens) AND large parent chunks (full sections, ~1,024 tokens). Index ONLY the small child chunk embeddings in the vector store. 2. **Retrieval**: Execute embedding similarity search on small child chunk embeddings — this gives high retrieval precision because small chunks have tightly-scoped embedding vectors. 3. **Context expansion**: Once the relevant child chunk is identified, retrieve its mapped parent chunk and pass the parent (large) chunk to the LLM. For detail queries: the small child chunk for Section 3.4.2 is retrieved precisely, and the parent section provides the full specification context. For synthesis queries: retrieving child chunks from multiple sections causes each query to return multiple parents, effectively loading multiple full sections into the LLM's context for cross-section synthesis. WHY NOT A: Uniform 4,096-token chunks improve synthesis queries but hurt detail queries. The large chunk's embedding vector averages signals from thousands of tokens, making it less precise for specific detail retrieval. A chunk covering 4,096 tokens of a complex spec will score lower similarity to a specific technical detail query than a 128-token chunk containing that exact detail. WHY NOT C: Sentence Window Retrieval expands context within a local N-sentence neighborhood. This works well for questions requiring a few surrounding sentences. However, for synthesis questions requiring content from two different sections (network layer + application layer), the N-sentence window around a network layer sentence would not capture the application layer section — the sections may be hundreds of tokens apart. WHY NOT D: Embedding the entire 500-page document as one chunk makes retrieval meaningless — all queries return the same single chunk, regardless of relevance. LLM long context windows (128K tokens) typically represent ~100 pages, not 500 pages, and processing a full spec on every query is extremely costly in latency and API tokens. This eliminates the purpose of chunking entirely. WHY NOT E: BM25 keyword retrieval is a complement to dense retrieval (useful in hybrid search), not a universal solution to dual granularity. For synthesis queries about cross-section relationships, keyword retrieval may return sections with overlapping technical terms but miss semantically related sections that use different vocabulary. Dense retrieval's semantic understanding is superior for synthesis-type questions.

8 Data Preparation

A generative AI engineer has completed text extraction and chunking of 5,000 PDF documents. Each chunk is represented as a Python dictionary: {'doc_id': str, 'chunk_index': int, 'chunk_text': str, 'source_filename': str, 'page_number': int}. The engineer needs to write all chunks to a managed Delta Lake table in Unity Catalog (catalog.schema.chunks_bronze) for use as the input to a vector embedding pipeline. Which sequence of operations is CORRECT?

  1. A1. Create a Python list of chunk dicts. 2. Convert to a pandas DataFrame. 3. Write directly to Unity Catalog using pandas_df.to_csv('catalog.schema.chunks_bronze'). 4. Confirm the table exists in Catalog Explorer.
  2. B1. Create a Python list of chunk dicts. 2. Convert to a spark.createDataFrame(chunk_list) PySpark DataFrame, defining the schema explicitly with StructType. 3. Write using df.write.format('delta').mode('overwrite').saveAsTable('catalog.schema.chunks_bronze'). 4. Verify the schema in Unity Catalog and confirm the table is registered under the correct catalog and schema.
  3. C1. Create the chunk dicts. 2. Serialize them to a JSON file on the local driver. 3. Upload the JSON file to a DBFS path. 4. Use spark.read.json('/dbfs/tmp/chunks.json') to create a DataFrame. 5. Write to Unity Catalog using .saveAsTable(). This is required because spark.createDataFrame() cannot accept Python lists directly.
  4. D1. Create the chunk dicts. 2. Write them directly to Unity Catalog with spark.sql("INSERT INTO catalog.schema.chunks_bronze VALUES " + str(chunk_list)). String interpolation into INSERT VALUES is the standard Databricks pattern for loading Python-generated data into Delta tables.
  5. E1. Register the chunks as a Pandas UDF output. 2. Apply the UDF to an empty DataFrame to produce the chunk rows. 3. Write the result to Unity Catalog. Pandas UDFs are required when loading non-Spark-native Python data structures into Delta.
Show answer & explanation

Correct answer: B

WHY B is correct: The canonical PySpark pattern for writing Python-generated data to a Unity Catalog Delta table is: Python list → spark.createDataFrame() → Delta write via saveAsTable(). spark.createDataFrame(chunk_list) directly accepts a list of Python dicts (or list of Row objects) and can infer or be given an explicit schema. saveAsTable('catalog.schema.chunks_bronze') registers the table in Unity Catalog under the three-level namespace (catalog.schema.table), making it a managed Delta table with full governance. Providing an explicit StructType schema is best practice to avoid type inference errors — especially for the chunk_index and page_number integer fields that could otherwise be inferred as long or nullable. WHY NOT A: pandas_df.to_csv() writes a CSV _file_ to a filesystem path, not to a Unity Catalog table. You would be writing the path string 'catalog.schema.chunks_bronze' as a local filename, not as a Unity Catalog table reference. CSV files are not Delta tables and are not registered in Unity Catalog's metastore. This approach fails both the Delta format requirement and the Unity Catalog registration requirement. WHY NOT C: spark.createDataFrame() absolutely CAN accept Python lists directly — this is a fundamental PySpark API capability. The DBFS intermediate step is unnecessary and adds I/O overhead. The claim that spark.createDataFrame() requires a serialized file is false. WHY NOT D: Building an INSERT VALUES SQL statement via Python string interpolation is dangerous (SQL injection risk, escaping issues with quotes in text), not scalable (SQL string length limits), and not idiomatic Databricks. The correct way to load a Python list is via spark.createDataFrame(), not string-constructed DML. For 5,000 multi-sentence chunks, the SQL string would be enormous and likely exceed Spark SQL statement size limits. WHY NOT E: Pandas UDFs are transformation functions applied to existing DataFrame columns — they are not a data loading mechanism. There is no standard pattern of 'apply a UDF to an empty DataFrame to generate data.' This answer describes a convoluted workaround that is not a documented pattern and would not work as described.

Take the full GenAI Engineer practice test →