Document Training • Published October 26, 2026 • Updated November 23, 2026 • 14 min read
Ingesting Structured Data into RAG: Parsing PDF Tables, CSV Product Catalogs, and JSON Schemas
Standard token chunkers slice right through CSV rows, strip table column headers, and fracture nested JSON keys. Learn how to serialize tabular and schema data for high-recall RAG—and when to route queries to SQL tools instead.
By Saad R. (Head of AI Engineering) • Fact-Checked & Empirically Tested
Executive Summary: Never pass raw CSVs, wide PDF tables, or deeply nested JSON through fixed-size character splitters. Convert CSV rows into self-describing key-value prose records, repeat Markdown pipe headers at the top of every split table chunk, flatten nested JSON paths, and route aggregations or live inventory arithmetic to parameterized SQL tool calls.
Why Standard Token Chunking Destroys Tabular and Schema Data
Enterprise knowledge bases rarely consist solely of narrative paragraphs. Customers upload 4,000-row CSV hardware catalogs, SaaS feature comparison matrices embedded inside PDFs, JSON configuration files, and OpenAPI specifications. When engineering teams feed those files into a standard 500-token recursive character splitter—the default configuration in most starter frameworks—retrieval accuracy collapses immediately.
To see why, trace what happens to a standard CSV pricing sheet when sliced at every 500 tokens:
- Chunk 1 (Rows 1–18) contains Row 1 (
sku,model_name,voltage_v,max_psi,unit_price_usd,lead_time_days) plus the first 17 items. - Chunk 2 (Rows 19–36) starts abruptly with raw comma-delimited literals:
IPS-440B, compact manifold sensor, 24, 350, 219.00, 14
Look at Chunk 2 from the perspective of both the embedding model and the LLM: every numeric column has lost its semantic schema. Is 24 the price in dollars, the lead time in days, the thread diameter in millimeters, or the operating voltage? Neither the vector model nor GPT-4o can tell without Row 1's header—and Row 1 lives back in Chunk 1, which wasn't retrieved! You can inspect this exact failure mode on sample CSVs and Markdown tables inside our RAG Chunk Visualizer.
The same structural destruction happens to PDF tables (where visual grid cells flatten into scrambled whitespace lines) and nested JSON documents (where splitting at line 120 severs leaf fields like "rateLimit": 1200 from their enclosing parent key "enterpriseTier" 80 lines higher). As we emphasize in our Semantic Chunking Guide, structured records require schema-preserving serialization before chunking.
Row-to-Prose Serialization for CSV Product Catalogs
Dense embedding models are trained overwhelmingly on natural language sentences and key-value technical documentation, not raw comma-delimited numbers. Converting each CSV or TSV row into a self-contained, schema-labelled record solves two problems simultaneously: every row carries its own explicit column names (plus units!), and dense embeddings align tightly with natural-language buyer questions like "How much does the 24V manifold sensor IPS-440B cost and what is its max pressure?".
Instead of indexing raw CSV lines, serialize each row using human-readable column labels, skip empty/null cells so "N/A" noise doesn't bloat tokens, and extract filterable attributes (price, category, in_stock) into vector store metadata:
import { parse } from "csv-parse";
import { Readable } from "node:stream";
/**
* Maps cryptic CSV header keys into explicit, unit-qualified display labels.
*/
const COLUMN_LABELS = {
sku: "SKU",
model_name: "Product Name",
category: "Category",
voltage_v: "Operating Voltage (V DC)",
max_psi: "Max Pressure Rating (PSI)",
unit_price_usd: "Unit Price (USD)",
in_stock: "Inventory Status",
lead_time_days: "Lead Time (Business Days)"
};
export async function serializeCsvCatalogForRag(csvBuffer, rowsPerChunk = 5) {
const parser = Readable.from(csvBuffer).pipe(
parse({
columns: true,
skip_empty_lines: true,
trim: true,
bom: true // Safely strip UTF-8 BOM exported by Excel
})
);
const serializedRows = [];
for await (const row of parser) {
const kvPairs = [];
for (const [rawCol, rawVal] of Object.entries(row)) {
if (rawVal === undefined || rawVal === null || rawVal === "") continue;
const label = COLUMN_LABELS[rawCol] || rawCol.replace(/_/g, " ");
let formattedVal = rawVal;
if (rawCol === "unit_price_usd" && !rawVal.startsWith("quot;)) {
formattedVal = `${Number(rawVal).toFixed(2)} USD`;
}
kvPairs.push(`${label}: ${formattedVal}`);
}
if (kvPairs.length === 0) continue;
serializedRows.push({
prose: kvPairs.join(" | "),
sku: row.sku || null,
category: row.category || "uncategorized",
priceNumeric: row.unit_price_usd ? Number(row.unit_price_usd) : null,
inStock: /^(true|yes|1|in stock)$/i.test(String(row.in_stock || ""))
});
}
// For single-SKU precision, 1-3 rows per chunk works best; group small related rows up to rowsPerChunk
const chunks = [];
for (let i = 0; i < serializedRows.length; i += rowsPerChunk) {
const slice = serializedRows.slice(i, i + rowsPerChunk);
chunks.push({
embeddingInput:
`[Product Catalog Records]\n` +
slice.map((item) => `- ${item.prose}`).join("\n"),
metadata: {
sourceType: "csv_catalog",
skus: slice.map((s) => s.sku).filter(Boolean),
categories: [...new Set(slice.map((s) => s.category))],
minPrice: Math.min(...slice.map((s) => s.priceNumeric ?? Infinity)),
maxPrice: Math.max(...slice.map((s) => s.priceNumeric ?? 0))
}
});
}
return chunks;
}
Engineering tip on rowsPerChunk: For rich product catalogs where each SKU has 8–15 attributes (descriptions, dimensions, compatibility notes, pricing), set rowsPerChunk = 1 so each SKU maps 1:1 to a single dedicated vector with exact SKU/price metadata! Only batch 5–10 rows per chunk when rows are ultra-compact lookup entries (like zip-code shipping zones or HTTP error code tables) that would otherwise create sub-25-token micro-chunks.
Extracting PDF Tables and Preserving Markdown Headers Across Chunks
Tables trapped inside PDFs are notoriously tricky because PDFs do not have <table> or <tr> tags—only vector ruling lines (re, m, l, S operators) or whitespace-aligned text runs. When extracting tables from technical datasheets or financial schedules, follow a two-part strategy:
- Grid & Whitespace Reconstruction + Merged Cell Propagation: Use a geometry-aware table extractor (
pdfplumberorDoclingin Python) that detects both ruled cell borders and borderless column alignments. Crucially, forward-fill merged vertical group cells (rowspan): financial and engineering tables frequently print a category name like" EMEA Cloud Region "only on the first row of a 6-row block, leaving rows 2–6 blank in Column 1. Propagating that group label into rows 2–6 ensures every extracted row remains self-identifying. - Header-Repeating Markdown Table Splitting: Modern LLMs parse GitHub-Flavored Markdown (GFM) pipe tables (
| Col A | Col B |) accurately—provided every chunk retains the table title, header row, and| --- |alignment separator. Never let a generic text splitter slice a 90-row Markdown table in half without re-injecting the header!
Here is a complete Python utility using pdfplumber that extracts clean Markdown pipe tables, forward-fills merged group cells, and splits tall tables into 15-row chunks with preserved headers on every single chunk:
import pdfplumber
from typing import List, Dict
def clean_cell(val) -> str:
if val is None:
return "-"
# Collapse internal newlines inside multi-line PDF cells so pipe syntax stays valid
return " ".join(str(val).replace("|", "\\|").split()).strip() or "-"
def split_markdown_table_preserving_headers(
headers: List[str],
rows: List[List[str]],
caption: str,
max_rows_per_chunk: int = 15
) -> List[str]:
header_line = "| " + " | ".join(headers) + " |"
separator_line = "| " + " | ".join(["---"] * len(headers)) + " |"
chunks = []
for start in range(0, len(rows), max_rows_per_chunk):
batch = rows[start : start + max_rows_per_chunk]
body_lines = ["| " + " | ".join(r) + " |" for r in batch]
part_label = f"{caption} (Rows {start + 1}-{start + len(batch)} of {len(rows)})"
chunk_md = "\n".join([f"### {part_label}", "", header_line, separator_line, *body_lines])
chunks.append(chunk_md)
return chunks
def extract_tables_from_pdf(pdf_path: str) -> List[Dict]:
extracted_chunks = []
with pdfplumber.open(pdf_path) as pdf:
for page_idx, page in enumerate(pdf.pages, start=1):
raw_tables = page.extract_tables({
"vertical_strategy": "lines_strict",
"horizontal_strategy": "lines_strict",
"intersection_tolerance": 5
}) or page.extract_tables() # Fallback for borderless whitespace tables
for tbl_idx, table in enumerate(raw_tables, start=1):
if not table or len(table) < 2:
continue
headers = [clean_cell(h) for h in table[0]]
normalized_rows = []
prev_first_col = "-"
for raw_row in table[1:]:
cleaned = [clean_cell(c) for c in raw_row]
# Skip completely empty separator rows
if all(c == "-" for c in cleaned):
continue
# Forward-fill merged category labels in Column 0 when sub-rows have values
if cleaned[0] == "-" and prev_first_col != "-" and any(c != "-" for c in cleaned[1:]):
cleaned[0] = prev_first_col
else:
prev_first_col = cleaned[0]
normalized_rows.append(cleaned)
caption = f"Page {page_idx} Table {tbl_idx}"
for md_chunk in split_markdown_table_preserving_headers(headers, normalized_rows, caption):
extracted_chunks.append({
"page": page_idx,
"table_index": tbl_idx,
"content": md_chunk
})
return extracted_chunks
When a table exceeds 10–12 columns horizontally (common in enterprise ERP exports or semiconductor pinout sheets), Markdown pipe tables become hard for LLMs to track across wrapped lines. For wide tables (columns > 10), switch automatically from pipe-table Markdown to the Key: Value | Key: Value row-to-prose serializer shown in Section 2.
Ingesting Nested JSON Payloads and OpenAPI Schemas
Developer documentation chatbots and internal platform assistants frequently need to answer questions over JSON configuration files, GraphQL schemas, or 15,000-line OpenAPI (swagger.json) specifications.
Raw JSON performs poorly under naive text chunking for two reasons: syntactic braces and quotes consume 25%–35% of your token budget without adding semantic signal, and splitting at line 200 detaches deeply nested properties (properties.webhook.retryPolicy.maxAttempts) from the API endpoint they belong to (POST /v2/webhooks/endpoints).
Instead, split structured JSON along domain entity boundaries (for OpenAPI: one chunk per (HTTP_METHOD, path) operation after resolving $ref pointers via @apidevtools/swagger-parser) and flatten nested configuration trees into dot-path key-value lines grouped by top-level section:
/**
* Flattens nested JSON objects into self-contextualized dot-path prose lines
* so every leaf property retains its full ancestor key path regardless of chunk split.
*/
export function flattenJsonToContextualLines(obj, prefix = "", out = []) {
if (obj === null || typeof obj !== "object") {
out.push(`${prefix}: ${JSON.stringify(obj)}`);
return out;
}
if (Array.isArray(obj)) {
if (obj.length === 0) {
out.push(`${prefix}: []`);
} else if (obj.every((item) => typeof item !== "object" || item === null)) {
out.push(`${prefix}: [${obj.map((v) => JSON.stringify(v)).join(", ")}]`);
} else {
obj.forEach((item, idx) => {
const itemKey = item?.id || item?.name || idx;
flattenJsonToContextualLines(item, `${prefix}[${itemKey}]`, out);
});
}
return out;
}
for (const [key, value] of Object.entries(obj)) {
const nextPath = prefix ? `${prefix}.${key}` : key;
flattenJsonToContextualLines(value, nextPath, out);
}
return out;
}
Look how clean flattenJsonToContextualLines() makes deeply nested schema leaves: billing.plans[enterprise].rateLimits.requestsPerMinute: 12000 Even if your chunker splits a 2,000-line configuration reference across 6 chunks, every single line carries its complete root-to-leaf path (billing.plans[enterprise]...), eliminating ambiguous keys like "enabled: true" floating out of context.
Vector Lookup vs. Hybrid SQL and Tool Calling for Exact Math
Knowing when NOT to use vector retrieval separates production AI architects from tutorial builders. Dense vector search retrieves the top-k (k = 5..15) semantically closest chunks—it cannot scan an entire 25,000-row table, sort numerically, or compute aggregates.
If a customer asks your e-commerce chatbot:
- "What is the operating temperature and warranty on SKU IPS-440B?" -> Vector + Lexical Hybrid RAG excels (single-entity lookup over serialized catalog prose).
- "How many 24V pressure sensors under $200 do you currently have in stock, and which one is the cheapest?" -> Pure Vector RAG WILL FAIL. Top-10 similarity search only sees 10 out of 400 matching sensors; if the cheapest $89 sensor ranked #18 in vector similarity, the LLM will confidently name the cheapest sensor among the 10 chunks it happened to see, giving a factually wrong answer!
Use this architectural routing matrix—covered further in our Complete RAG Architecture Guide and Platform Documentation—when designing structured data workflows:
| Query Pattern | Example User Utterance | Pure Vector RAG | Metadata-Filtered RAG | SQL / API Function Tool |
|---|---|---|---|---|
| Single SKU / Spec Lookup | "Does the X200 sensor support 24V DC?" | High Accuracy | High Accuracy | High Accuracy |
| Qualitative Feature Match | "Which sensor resists saltwater corrosion?" | High Accuracy | Best (with category filter) | Poor (needs full-text prose) |
| Bounded Range Discovery | "Recommend 3 waterproof sensors under $250" | Unreliable alone | High (WHERE price < 250) | High |
| Global Aggregation / Math | "Count all SKUs out of stock in Warehouse B" | Fails (Top-K blindspot) | Fails | *Required (SELECT COUNT())** |
| Real-Time Mutable State | "Where is my order #98412 right now?" | Fails (Stale index) | Fails | Required (Live Order API) |
In production, pair your vectorized prose catalog with read-only, parameterized tool functions (never raw unrestricted LLM-generated DROP/UPDATE SQL—bind structured tool arguments like { maxPrice: 200, voltage: 24, sortBy: "price_asc", limit: 5 } into prepared read-only queries) and instruct the assistant in your System Prompt Builder to invoke the catalog filter tool whenever a user asks for "cheapest", "all", "how many", or "under $X".
Production Failure Modes with Structured Data and Fixes
Watch for these three subtle tabular bugs during staging QA:
Failure Mode 1: Checkmark Symbols (✓, ✗) Vanishing from Comparison Matrices
- Symptom: On a SaaS pricing comparison PDF table (
Starter | Pro | Enterprise), the chatbot claimed none of the plans included SOC 2 reports—even though the Enterprise column clearly had a green checkmark! - Root Cause: Designers rendered checkmarks using custom icon glyphs (FontAwesome, Wingdings, or inline SVG paths) rather than Unicode
✓(\u2713) or text"Included". The PDF text parser extracted empty cells| SOC 2 Report | - | - | - |. - Fix: Inspect extracted comparison matrices before indexing. When ingesting graphical feature grids, either convert source HTML/DOCX tables directly (mapping
.icon-checkclasses to explicit"Included"and.icon-crossto"Not Included"), or use a vision-language table parser (gemini-2.5-flash/DoclingVLM table mode) for graphic-heavy marketing PDFs.
Failure Mode 2: Dense Embeddings Missing Exact Alphanumeric Part Numbers
- Symptom: Searching
"IPS-440B-REV2"returned chunks for"IPS-440A-REV1"and"IPS-450B"with nearly identical dense cosine similarity, pushing the exact SKU down to rank #7. - Root Cause: Dense embedding models compress semantic meaning into continuous space where neighbouring alphanumeric part codes look almost indistinguishable.
- Fix: Always combine dense vector search with Reciprocal Rank Fusion (RRF) over BM25 / exact SKU metadata boosts so exact alphanumeric token matches jump straight to Rank #1.
Failure Mode 3: Unitless Numeric Cells Misread Across Merged Tables
- Symptom: A logistics rate table listed
"45"under a header footnote"*All weights in kg; rates in EUR", causing the bot to quote"$45 USD"to US visitors. - Fix: Capture table footnotes (
*,†) situated immediately beneath</table>or PDF table bounding boxes and append them directly to every split chunk of that table alongside explicit unit headers (Rate (EUR),Max Weight (kg)).
Frequently Asked Technical Questions
Should I embed CSV files directly or query them with Text-to-SQL?
Use a hybrid design matched to query intent. If users ask qualitative, semantic questions over descriptive columns ('Which valve works best with corrosive acids?'), serialize each CSV row into labelled prose and index it in your vector store. If users ask for counts, sums, min/max sorting, or strict multi-column filtering across thousands of rows, expose parameterized SQL or API filter tools instead.
What is the best format for feeding tables into an LLM prompt: Markdown, JSON, or HTML?
For tables with up to 10 columns, GitHub-Flavored Markdown pipe tables offer the best balance of low token overhead and high LLM comprehension—provided every split chunk repeats the header and separator rows. For wide tables exceeding 10 columns, serialize each row into 'Column Name: Value | Column Name: Value' prose lines so values never misalign horizontally.
How many CSV rows should I pack into a single RAG vector chunk?
For rich product or service catalogs where each row represents a distinct entity with 6 or more fields, index 1 row per chunk (or at most 2–3 closely related variants) and attach SKU, category, and price as filterable metadata. Grouping 30 unrelated products into one chunk dilutes the chunk's vector embedding and wastes LLM context tokens.
Why does vector search struggle to find exact SKU codes and serial numbers?
Dense embedding models optimize for conceptual similarity rather than character-by-character string identity, so BPE subword tokenization makes 'SKU-8841-A' and 'SKU-8842-B' map to nearly identical vectors. Fix this by enabling hybrid retrieval (combining dense embeddings with BM25 keyword search via Reciprocal Rank Fusion) and indexing SKU identifiers in an exact-match metadata field.