How RAG Handles Tables and Charts in Documents: A Complete Guide
This article explains why tables and charts are difficult for Retrieval-Augmented Generation (RAG) systems and presents a practical three-stage pipeline for handling them: reading, conversion, and concatenation. You will learn how to preserve table structure during extraction, why HTML is preferred over Markdown or JSON for representing merged cells and header hierarchies, and how to embed tables back into their surrounding context. The article also covers retrieval and generation best practices, common pitfalls, and evaluation strategies for improving answer accuracy without model training.
1. Why Tables and Charts Are the Hard Part of RAG
In a Retrieval-Augmented Generation (RAG) system, the plain-text pipeline is relatively mature: chunking, embedding, retrieval, reranking, context assembly, and answer generation. But real enterprise documents are never purely linear text. Pricing adjustment rules, rate schedules, parameter comparison tables, flowcharts, bar charts, and line charts often carry the highest density of critical information in a document. If that structure is lost during parsing, even the best retriever and the strongest model can only produce answers that “look right but are actually wrong.”
The core challenges of chart and table processing come down to two points:
- Structural fidelity: A table’s meaning comes not only from cell text but also from the 2D relationship between rows and columns, the hierarchy of merged cells, and the mapping between headers and data. Flattening row by row erases these relationships.
- Semantic interpretability: Retrieved vectors are fed back to the LLM, which must be able to “read” the structure rather than seeing a pile of misaligned data and improvising.
A typical counter-example is a table with merged cells. If it is extracted row by row as plain text, the first header row may have “Adjustment Logic” spanning two columns, while the second data row has only one value in the corresponding position. The model cannot tell which column that value modifies. With vertical merges (rowspan), the first column of subsequent rows becomes empty, and the model may assume the row is missing a field and fabricate content.
2. The Overall Approach: A Three-Stage Read, Convert, and Concatenate Pipeline
A reliable industry practice is to split chart processing into three clearly separated stages, each doing one job, which makes problems easier to isolate.
2.1 Read: Detect Table Boundaries and Raw Structure
The goal of the reading stage is not to “get the text” but to obtain a raw representation that carries structure. It needs to:
- Layout analysis: Distinguish body paragraphs, table regions, and image regions, avoiding treating captions as body text or tables as paragraphs.
- Table structure recognition: Identify the number of rows, columns, cell spans (colspan/rowspan), and header levels.
- Cell text extraction: Preserve original characters such as in-cell line breaks, units, plus/minus signs, and percent signs, without normalization or cleaning, so that “±3.00%” is not truncated to “3”.
An illustrative intermediate structure can be expressed as:
{"type": "table","rows": 3,"cols": 6,"cells": [{"r": 0, "c": 0, "text": "Case", "rowspan": 1, "colspan": 1},{"r": 0, "c": 3, "text": "Adjustment Logic", "rowspan": 1, "colspan": 2}]}
Key point: Span information must be preserved at this layer. Once discarded, no downstream algorithm can reconstruct it.
2.2 Convert: Express 2D and Hierarchical Relationships with HTML
Why choose HTML instead of Markdown tables or JSON? Because HTML natively supports colspan, rowspan, thead, and tbody. It can express merges while distinguishing the header from the data body, and LLMs generally parse HTML tables well. Markdown tables cannot express merged cells; pure JSON is precise but has high token overhead and models easily misread the hierarchy.
The basic idea of the conversion algorithm is “placeholder + expansion”:
- Scan row by row; when a cell with
rowspan>1is encountered, write a placeholder marker in the corresponding column of subsequent rows; - When
colspan>1is encountered, keep the span attribute in the header or data row; - Output a valid
<table><thead>...</thead><tbody>...</tbody></table>.
Example code:
def to_html(table):html = ["<table><thead>"]# Header rowshtml.append("<tr>")for cell in table.header:attr = ""if cell["colspan"] > 1: attr += f' colspan="{cell["colspan"]}"'if cell["rowspan"] > 1: attr += f' rowspan="{cell["rowspan"]}"'html.append(f"<th{attr}>{cell['text']}</th>")html.append("</tr></thead><tbody>")# Data rows: skip columns occupied by rowspanoccupied = {}for r, row in enumerate(table.body):html.append("<tr>")for c, cell in enumerate(row):if occupied.get((r, c)): continueattr = ""if cell["rowspan"] > 1:attr += f' rowspan="{cell["rowspan"]}"'for k in range(1, cell["rowspan"]): occupied[(r+k, c)] = Trueif cell["colspan"] > 1: attr += f' colspan="{cell["colspan"]}"'html.append(f"<td{attr}>{cell['text']}</td>")html.append("</tr>")html.append("</tbody></table>")return "".join(html)
The converted table preserves the membership relationship of “which case a row belongs to” and makes it clear to the model that “this cell spans three rows downward.”
2.3 Concatenate: Put the Table Back into Its Original Context
An isolated table is semantically incomplete. The same “5.50%” can mean completely different things in different sections. Therefore, the concatenation stage embeds the table into its context: the section heading it belongs to, the introductory sentence before it, table notes, and unit explanations.
The recommended structure is:
{Section number and heading}{Introductory paragraph before the table}{Table HTML}{Supplementary notes/caption after the table}
This way, during vectorization, the table, heading, and notes together form a semantically complete chunk; at retrieval time, the model receives a “structured fragment with context” rather than a bare table.
3. Supporting Design for Retrieval and Generation
- Chunking strategy: Keep tables whole within a chunk whenever possible to avoid cross-chunk truncation; for oversized tables, split by “header + several rows” and repeat the header so each chunk is self-explanatory.
- Metadata: Attach metadata such as document name, section path, table type, and page number to each chunk for filtering and traceability.
- Post-retrieval processing: Apply reranking boosts to table-type chunks, since charts and tables are often the key evidence for question answering.
- Prompt constraints: Explicitly instruct the model to “answer only based on the given HTML table, and respond that it cannot confirm if information is insufficient” to suppress fabrication.
- Answer citations: Include section and table location in the output to facilitate manual verification.
4. Common Pitfalls and Evaluation Recommendations
- Incorrect merged-cell reconstruction: Focus on checking the rowspan placeholder logic.
- Lost units and symbols: Do not clean data during the reading stage.
- Confused header levels: Merge multi-row headers into a single thead or add level prefixes.
- Image-based charts: First perform layout and chart-type recognition, then convert to a structured description or data table; relying only on OCR text is not enough.
- Evaluation: Build a QA set containing merged tables, multi-row headers, and image charts, and separately measure structure reconstruction accuracy and end-to-end answer accuracy to determine whether the issue lies in parsing or generation.
5. Conclusion
The essence of chart processing is finding an engineering balance between “information fidelity” and “model readability.” The reading stage preserves structure, the conversion stage expresses hierarchy with HTML, and the concatenation stage restores context. Combined with retrieval and prompt constraints, this enables RAG to give reliable answers to complex tables and charts without any model training.
