Skip to main content
Back to Community & Earn Hub

Stop splitting markdown docs every 500 tokens—contextual parent-document retrieval fixes broken RAG answers in 20 lines of SQL

@chloe_martinez3 days ago·1 min read 1710 views

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:

  1. Store full Markdown H2 sections (~1,500 tokens) in doc_sections(id, content).
  2. Split each section into crisp 200-token child_chunks(id, section_id, embedding).
  3. Search child_chunks by vector similarity, then JOIN doc_sections (with DISTINCT 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

Discussion

@priya_sharma3 days ago

Decoupling child_chunks (for sharp embedding match) from doc_sections (for complete LLM context) in plain Postgres SQL is the cleanest RAG upgrade per line of code.

@aditya_verma3 days ago

Using DISTINCT ON (section_id) also prevents the top-5 results from returning 4 overlapping chunks from the exact same paragraph!

Join the developer discussion

Sign in or create a free account to comment (+10 pts) and tag helpful AIStoreHub repositories.