Chunking strategies and versioned embeddings in pgvector
Compare token-window and heading-based chunking and store versioned embeddings in pgvector that survive a model change.
By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 12 minutes to read.
In short
Documents are split into chunks small enough to retrieve and quote, then each chunk is turned into an embedding: a list of numbers that places similar meanings close together. Token-window chunking cuts fixed-size pieces with overlap; heading-based chunking follows the document's own structure. Storing the model name and dimension with every embedding lets you change models without mixing incompatible vectors.
Think of it like this: Chunking is cutting a manual into index cards; embedding is pinning each card on a map where cards about similar things sit near each other.
Explained simply
A whole document is usually too long to hand to a model, and most of it is irrelevant to any one question. So we cut documents into chunks: pieces of a few hundred tokens. A token is the unit models count text in, roughly three quarters of an English word on average.
There are two common ways to cut. A token window takes a fixed number of tokens, then starts the next chunk a little before the end of the last one, so no sentence is lost at the edge. Heading-based chunking makes one chunk per section, following the document's own structure.
Each chunk is then turned into an embedding. An embedding model reads the text and returns a list of numbers, for example 384 or 1536 of them. Texts with similar meaning get similar lists. Search then becomes finding the stored lists closest to the question's list.
Every embedding model makes its own kind of list. Numbers from one model cannot be compared with numbers from another, even if the lengths match. That is why each stored embedding records which model made it, and why switching models means re-embedding everything.
Press Play on a diagram to walk through it one step at a time.
- Fixed size, such as 300 tokens
- Overlap of 10 to 20 percent
- Ignores headings
- Simple and predictable size
- One chunk per section
- Keeps a rule and its context together
- Sizes vary a lot
- Long sections need a fallback split
- 1Section
KB-0042#refund-window, version 3
- 2Chunk
Split and count tokens
- 3Embed
Model returns N numbers
- 4Store
Vector plus model name and dimension
- 5Index
HNSW index per model
- Too small (under 100 tokens)
- Loses conditions and context
- More rows and vectors
- Answers need many chunks
- Balanced (200 to 500 tokens)
- One idea per chunk
- Predictable budget
- Too large (over 1,000 tokens)
- Relevant sentence diluted
- Fewer chunks fit the budget
- May exceed model input limit
In depth
Token window versus heading-based chunks
Token-window chunking is simple: count tokens, cut every N, overlap by 10 to 20 percent. Every chunk is a similar size, which makes the context budget predictable. The cost is that a cut can separate a rule from its condition, such as a refund limit from the sentence saying it only applies to annual plans.
Heading-based chunking respects the author's structure, so a section like Exceptions stays whole. Support articles often have short, focused sections, which suits this well. The weak spots are very short sections that lack context and very long ones that exceed the embedding model's input limit. A practical hybrid is: chunk by heading, then split any section over the limit with a token window, and prefix every chunk with its document title and heading.
- Typical window: 200 to 500 tokens with 10 to 20 percent overlap
- Prefix chunks with title and heading before embedding
- Split oversize sections with a token window
- Measure both strategies on the same question set
Storing vectors in pgvector
pgvector adds a vector type to PostgreSQL. A column declared vector(384) only accepts 384 numbers, which protects you from mixing dimensions by accident. Distance operators compare vectors: <-> is Euclidean distance, <=> is cosine distance and <#> is negative inner product. Many embedding models return vectors normalized to length 1, and for those all three give the same ordering.
Without an index, a query compares the question with every row, which is exact and fine for a few thousand chunks. For more, add an approximate index. HNSW builds a graph and usually gives better speed and recall; IVFFlat builds faster and uses less memory. The index must use the operator class that matches your query operator, such as vector_cosine_ops for <=>.
- vector type: up to 16,000 dimensions stored
- HNSW and IVFFlat on vector: up to 2,000 dimensions
- halfvec can index up to 4,000 dimensions
- Exact scan is fine for a small lab corpus
Versioning embeddings so a model change is safe
Treat an embedding as derived data with its own version: chunk_id, model name and dimension. When you change model, nothing about the source documents changed, but every vector is now incompatible. The safe migration runs side by side. Create a new column or table for the new model, fill it in the background, build its index, run your retrieval evaluation on both, and only then switch the query to the new model. Keep the old vectors until the switch has proven itself, then drop them.
pgvector also lets one untyped vector column hold several dimensions, with a partial expression index per model that casts to the right size. That keeps one table but needs care in every query to filter by model.
- 1Add store
New table or column for model B
- 2Backfill
Embed all chunks with model B
- 3Index
Build HNSW for model B
- 4Evaluate
Compare recall@k for A and B
- 5Switch reads
Queries use model B
- 6Retire A
Drop old vectors later
A deterministic stub for local labs
Hosted embedding APIs cost money per token and need an account, and local models need a download and some memory. For the labs, a stub embedder is enough: hash each word into one of 384 buckets, count, and normalize the vector. It is not smart, so synonyms will not match, but it is fully deterministic, free and fast, which makes tests repeatable.
The stub is also a good teacher. Because it only knows words, it shows exactly where real semantic embeddings add value. When you later plug in a real model, optional and possibly paid, only the embed function and the model name change; the tables, IDs and migration steps stay the same.
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Chunk by token window and by heading~1h
- 2Store embeddings with model and version~1h
- 3Choose vector dimensions and an index~1h
- 4Re-embed when the model or dimension changes~1h
Key points
- Chunk IDs should be derived from doc_id, version and section, so the same input always gives the same IDs.
- Put the document title and section heading into the chunk text you embed; it adds context a bare paragraph lacks.
- Vectors from different models live in different spaces and must never be compared with each other.
- In pgvector, HNSW and IVFFlat indexes on the vector type support up to 2,000 dimensions.
- Changing the model or dimension means re-embedding every chunk and building a new index before switching reads.
Key terms
Tap a card to flip it. 0/6 known
Examples
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE chunk_embeddings (
chunk_id text NOT NULL REFERENCES chunks(chunk_id) ON DELETE CASCADE,
model text NOT NULL, -- e.g. 'stub-hash-384' or a hosted model name
dim int NOT NULL,
embedding vector(384) NOT NULL,
PRIMARY KEY (chunk_id, model)
);
CREATE INDEX ON chunk_embeddings USING hnsw (embedding vector_cosine_ops);The dimension is part of the column type, so a 768-dimension model needs a new column or table.
A deterministic stub embedder
Step 1: lower-case the text and split it into words. Step 2: hash each word with SHA-256 so the result does not change between runs (Python's built-in hash does change). Step 3: add one to the bucket the hash picks. Step 4: divide by the vector length so it has length 1. Expected evidence: embedding the same text twice gives identical lists, and two texts sharing many words get a cosine similarity close to 1.
import hashlib, math, re
DIM = 384
def embed(text: str) -> list[float]:
vec = [0.0] * DIM
for word in re.findall(r"[a-z0-9-]+", text.lower()):
h = int(hashlib.sha256(word.encode()).hexdigest(), 16)
vec[h % DIM] += 1.0
norm = math.sqrt(sum(v * v for v in vec)) or 1.0
return [v / norm for v in vec]Heading-first chunking with a size fallback
Contoso's Exceptions section is 900 tokens, over the 500 limit. Step 1: create one chunk per section. Step 2: any section longer than the limit is split into windows of 400 with 60 overlap. Step 3: each chunk gets the title and heading as a prefix and an ID ending in a sequence number. For simplicity, words stand in for tokens here; use the answer model's tokenizer in real code.
def chunk_section(doc: dict, sec: dict, limit=500, size=400, overlap=60):
words = sec["body"].split()
if len(words) <= limit:
windows = [words]
else:
step = size - overlap
windows = [words[i:i + size] for i in range(0, len(words), step)]
prefix = f"{doc['title']} > {sec['heading']}\n"
for n, w in enumerate(windows):
yield {
"chunk_id": f"{doc['doc_id']}:v{doc['version']}:{sec['section_id']}:{n}",
"text": prefix + " ".join(w),
}Quick reference
- Chunk ID = doc_id:vVERSION:section_id:n, deterministic on every run
- Typical chunk: 200 to 500 tokens, 10 to 20 percent overlap
- pgvector operators: <-> L2, <=> cosine distance, <#> negative inner product
- Index opclass must match the operator, e.g. vector_cosine_ops for <=>
- HNSW/IVFFlat index on vector: max 2,000 dimensions; halfvec: 4,000
- Never compare vectors from two different embedding models
- New model: backfill, index, evaluate, then switch reads
Common mistakes
- Querying with a vector from a new model against vectors from the old model; results look plausible but are noise.
- Chunks so large that the one relevant sentence is diluted, or so small that the rule loses its condition.
- Forgetting that heading-based chunks can exceed the embedding model's input limit.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Chunk your three Contoso documents both ways, by 100-word windows with 20-word overlap and by heading, and print the chunk count and largest chunk for each strategy.
- Exercise 2medium
Store stub embeddings in pgvector and run a nearest neighbour query for 'how long do I have to ask for my money back'.
- Exercise 3hard
Simulate a model change: add a 'stub-hash-768' model in a second table, backfill it, and switch queries with a single configuration value. Show that querying the 768 table with a 384 vector fails loudly.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What chunk size should I use?
- Start around 300 tokens with some overlap or one chunk per section, then measure recall on your own question set. There is no universal best size.
- Do I need a paid embedding API?
- No. The labs use a free deterministic stub. Hosted APIs (paid per token) or local open models are optional upgrades that change only the embed function.
- Should I use HNSW or IVFFlat?
- HNSW is the usual default for query speed and recall. IVFFlat builds faster and uses less memory, but should be created after the table has data. For small corpora, no index is fine.
- Can one column store vectors of different sizes?
- Yes, with an untyped vector column, but you then need a filtered expression index per model and must filter by model in every query.