Sub topic 6
Embeddings and chunking your documents
This chapter assumes you know basic Python, how large language models take prompts, and what a Delta table is. You should also have a rough idea of what similarity search does. Here you will prepare documents so that Vector Search, covered in the next chapter, can index them.
What an embedding is
An embedding is a list of numbers (a vector) that represents the meaning of a piece of text. Texts with similar meaning produce vectors that sit close together. Similarity search compares the vector of a question with the vectors of your documents and returns the closest ones.
An embedding model produces these vectors. On Databricks you call one through a serving endpoint, the same way you call a chat model. Vector Search can call that endpoint for you, so you rarely compute vectors by hand.
Why you chunk documents
An embedding model has a maximum input length, and one vector for a whole manual blurs many topics together. A chunk is a smaller piece of a document, sized so that it covers one idea. Each chunk gets its own vector and its own row in a Delta table.
Chunk size is a trade-off:
| Chunk size | Benefit | Risk |
|---|---|---|
| Too small | Precise matches | Loses surrounding context, so the model sees fragments |
| Too large | Keeps context | Vector mixes topics, retrieval gets vague, prompts get long |
A common starting point is 500 to 1,000 characters per chunk with a 10 to 20 percent overlap. Overlap repeats the end of one chunk at the start of the next. It keeps a sentence that straddles a boundary from being cut off from its meaning.
A simple chunker
The function below splits text into overlapping character windows. It is deliberately simple. Production pipelines often split on paragraphs or headings first, so chunks follow the document's structure.
def chunk_text(text: str, size: int = 800, overlap: int = 100) -> list[str]:
if overlap >= size:
raise ValueError("overlap must be smaller than size")
chunks = []
step = size - overlap
for start in range(0, len(text), step):
piece = text[start:start + size].strip()
if piece:
chunks.append(piece)
return chunks
sample = "Vector indexes store embeddings. " * 100
pieces = chunk_text(sample)
print(len(pieces), len(pieces[0]))Writing chunks to a Delta table
Store each chunk with a stable primary key and the text. Vector Search needs a primary key, and a Delta Sync index also needs Change Data Feed enabled on the source table so it can track updates.
rows = [
(f"doc1-{i}", "doc1", chunk)
for i, chunk in enumerate(chunk_text(sample))
]
df = spark.createDataFrame(rows, schema="id string, source string, text string")
df.write.mode("overwrite").saveAsTable("main.genai.docs_chunks")
spark.sql(
"ALTER TABLE main.genai.docs_chunks "
"SET TBLPROPERTIES (delta.enableChangeDataFeed = true)"
)The spark object is available by default in Databricks notebooks. Keeping a source column lets you show citations later.
Common errors
- Embedding model mismatch. Queries and documents must use the same embedding model. Changing the model means rebuilding the index.
- Missing Change Data Feed. Creating a Delta Sync index on a table without it fails.
- Duplicate or changing IDs. Derive IDs from the source and position so reruns update rows instead of duplicating them.
- Chunks that ignore structure. Splitting mid-table or mid-code block produces chunks that retrieve poorly. Split on structure first.
- Overlap too large. Heavy overlap inflates storage and returns near-duplicate results.
Exercise
A table of chunks uses 2,000-character chunks with no overlap. Retrieval often returns text that starts in the middle of a sentence and answers are incomplete. Name two changes you could make and why each helps.
Show answer
Add overlap (for example 10 to 20 percent) so sentences that cross a boundary appear whole in at least one chunk. Also split on paragraph or heading boundaries, or use smaller chunks, so each chunk holds one complete idea rather than an arbitrary slice.