Stop splitting markdown docs every 500 tokens—contextual parent-document retrieval fixes broken RAG answers in 20 lines of SQL
Every RAG engineer hits the Chunk-Size Paradox:
- Small chunks (150–250 tokens): Vector embeddings are razor-sharp and match specific queries accurately—but the retrieved snippet is too short, cutting off critical caveats or code blocks 10 lines down!
- Large chunks (1,500–2,000 tokens): Give the LLM complete context—but dilute the single embedding vector across 4 different subtopics so cosine search misses the query!
The 20-Line SQL Fix: Parent-Document Retrieval
Decouple what you embed from what you feed the LLM:
- Store full Markdown H2 sections (~1,500 tokens) in
doc_sections(id, content). - Split each section into crisp 200-token
child_chunks(id, section_id, embedding). - Search
child_chunksby vector similarity, thenJOIN doc_sections(withDISTINCT ON (section_id)) to hand the LLM the complete parent section!
Zero extra vector databases, zero complex pipelines—just clean relational modeling in Postgres.
2 Comments