Handling Images and Tables in RAG Vector Databases
Images and tables require more than a stronger embedding model to work reliably in retrieval-augmented generation. This article explains how to preserve document structure, choose suitable vector representations, chunk and index non-text content, and assemble retrieved evidence for generation. It also covers evaluation, incremental updates, and common implementation pitfalls.
1. The Core Problem: Parsing and Representation, Not Just Embeddings
In retrieval-augmented generation (RAG), problems with non-text content are often reduced to “text embedding models cannot understand images.” That is only part of the issue. The real gaps occur at three stages:
- Parsing: When content is extracted from PDFs or scanned documents, tables may become unstructured character streams, losing row and column relationships. Images may be reduced to placeholders.
- Representation: Even when parsing is correct, embedding an entire table as a single vector can dilute its meaning with large amounts of numeric data and short labels. Images without links to surrounding context become isolated noise.
- Alignment: If text and visual embeddings come from different vector spaces, placing them in the same index does not make their similarity scores comparable. Retrieval rankings can become unreliable.
The engineering sequence should therefore be: reconstruct the layout as a structured intermediate representation, choose how to vectorize it, and then design retrieval and source-content assembly. Replacing the embedding model with a multimodal model before fixing parsing usually preserves the same noise in a different form.
2. Parsing: Reconstruct a Structured Intermediate Representation
The goal is an intermediate format that preserves information and makes structure explicit, rather than producing plain text. A common approach combines Markdown with a structured JSON sidecar.
The parsing layer needs to cover several capabilities:
- Layout and reading order: Restore multicolumn layouts and identify the relationships between headers, footers, footnotes, and figure captions. Avoid interleaving text from separate columns.
- Table structure: Handle bordered and borderless tables, tables spanning multiple pages, expanded merged cells, dense small-font tables, and content mixing handwriting and formulas. Output explicit rows and columns, not pseudo-tables aligned with spaces.
- Image semantics: For each image, capture or generate a caption, extract embedded text with OCR, and associate relevant surrounding passages. This creates an image–description–reference-location relationship.
- Format robustness: Aim for consistent parsing quality across fonts, PDF encodings, scanned documents, and digitally generated files.
An illustrative intermediate representation:
{"block_id": "p12-t3","type": "table","page": 12,"caption": "Quarterly revenue by region","markdown": "| Region | Q1 | Q2 |\n|---|---|---|\n| East | 120 | 138 |","rows": 2, "cols": 3,"context_before": "The following table compares quarterly revenue across regions...","bbox": [72, 340, 520, 610]}
Fields such as caption, context_before, and bbox provide reliable anchors for embedding, retrieval, and source attribution.
3. Representation: Three Vectorization Strategies
Strategy 1: Convert to Text, Then Embed
This is the default starting point.
Convert tables into Markdown or natural-language statements, typically one statement per row. Represent images using their captions, OCR text, and summaries of surrounding context.
This approach reuses established text embedding and retrieval infrastructure. It is relatively inexpensive and easy to interpret. Its main limitation is the loss of visual details such as trends, colors, and spatial layout.
Strategy 2: Use Joint Vision–Language Representations
Use a vision–language model with a shared vector space to encode images into vectors comparable to text embeddings, enabling cross-modal retrieval.
This approach suits image-heavy knowledge bases containing drawings, charts, or product images. It increases indexing costs and requires evaluating the model’s coverage of the source language, including Chinese where applicable, and specialized terminology.
Strategy 3: Combine Multiple Representations
A hybrid approach is recommended for production environments.
Generate multiple representations and indexes for the same object: text embeddings for body text, structured-summary embeddings for table and image descriptions, and multimodal embeddings for original images. Combine them with scalar metadata fields.
def index_block(block):records = []if block.type == "table":records.append(vec(embed(block.caption + "\n" + to_sentences(block))))records.append(vec(embed(summarize(block.markdown)), kind="table_summary")elif block.type == "image":records.append(vec(embed(block.caption + block.ocr_text)))records.append(vec(embed_vl(block.image), kind="multimodal"))for r in records:r.meta = {"doc_id": block.doc_id, "page": block.page,"type": block.type, "acl": block.acl}return records
The example illustrates the indexing flow: one source block can produce several retrieval representations while retaining shared provenance and access-control metadata.
4. Chunking and Indexing: Do Not Split Tables by Character Count
- Keep tables intact where possible. Split very large tables into a header plus groups of rows. Repeat the header in every chunk so each chunk remains understandable on its own.
- Use parent–child chunks. Retrieve child chunks for precision, then supply the parent section or complete table to the model for context.
- Maintain complete metadata. Include document ID, page number, block type, version, and access-control labels to support filtered retrieval and incremental updates.
- Store original files and parsing outputs in object storage. Keep pointers rather than large payloads in the vector database. This makes index rebuilding and staged embedding-model changes easier.
5. Retrieval and Generation: Make Non-Text Evidence Usable
Retrieving a table or image representation is not enough. The generation stage must receive the evidence needed to answer the question.
- Hybrid retrieval: Use dense vectors for semantic similarity and sparse retrieval, such as term-frequency-based methods, for exact matches on numbers, model identifiers, and proper nouns. This is particularly useful for tables.
- Metadata prefiltering: Narrow candidates by document, time, permissions, and block type. This limits inappropriate cross-modal comparisons, though it does not itself align incompatible embedding spaces.
- Reranking: Use a cross-encoder to score candidates from multiple retrieval paths on a common basis before selecting content for the context window.
- Source-content assembly: When a table is retrieved, insert its original Markdown into the prompt. When an image is retrieved, include its caption and OCR text. Preserve
pageandblock_idfor traceable citations.
Context assembly order:Question → Retrieved parent text blocks → Retrieved tables (original Markdown) → Image descriptions → Citation list
Summaries help retrieve relevant material, but the original table content is needed when the answer depends on specific values.
6. Evaluation and Operations
- Include non-text questions in evaluation sets. Build separate sets for numeric questions such as “What was Q2 revenue for the East region?”, cross-table comparisons, and caption-based questions. Measure retrieval recall and answer accuracy separately.
- Attribute failures by stage. Distinguish parsing errors, chunking errors, representation errors, and retrieval or ranking errors. Diagnose each layer instead of attributing every failure to the model.
- Make updates incremental and idempotent. Use content fingerprints to trigger reparsing and re-embedding when documents change. Handle deletions through soft deletion and index rebuilding to prevent drift between the index and source documents.
- Control costs. Apply parsing, embedding, and reranking selectively by processing tier, and cache parsing outputs for frequently accessed documents.
7. Common Pitfalls
- Flattening tables into space-aligned text and losing row–column relationships.
- Failing to join tables across pages, leaving chunks without headers or complete meaning.
- Indexing images without their captions or surrounding context, creating isolated content that is difficult to retrieve.
- Mixing text and visual vectors without alignment or appropriate score handling; score normalization alone does not make unrelated vector spaces compatible.
- Retrieving summaries but not supplying original content, leaving the model unable to answer questions about specific values.
- Omitting block-level provenance, making answers difficult to verify and reducing user trust.
Conclusion
Handling non-text content in RAG is not simply a matter of choosing a stronger embedding model. It requires an end-to-end pipeline covering layout parsing, structured intermediate representations, multiple vectorization paths, hybrid retrieval, and source-content assembly.
Reliable parsing, clear semantic anchors for tables and images, and alignment between retrieval and generation are the foundations for consistent, reproducible improvements in numeric question answering and chart understanding.
