Handling Images and Tables in Vectorization for LLM RAG Systems
This article explains why images and tables cause retrieval gaps in LLM RAG systems and how to address them across six stages: parsing, representation, chunking, indexing, retrieval, and evaluation. It covers layout-aware document parsing, three representation routes (multimodal embeddings, text-based stand-ins, and structured summaries with field-level indexing), semantic chunking rules, multi-collection indexing with metadata filtering, hybrid retrieval with reranking, and category-specific evaluation. The goal is to treat non-text elements as first-class citizens so vector databases capture the full information in enterprise documents.
When building an LLM RAG (Retrieval-Augmented Generation) system, the quality of the vector database largely determines the ceiling of the final answer. Yet real enterprise documents are never clean text streams: product manuals contain diagrams, financial reports contain tables with multi-level headers, and scanned contracts include stamps and annotations. If the ingestion stage extracts plain text only, the critical information carried by images and tables is lost during retrieval, showing up as “the document clearly has it, but the model cannot answer.” This article takes a general technical perspective and systematically discusses how to carry non-text information such as images and tables when creating a vector store from documents. It covers six stages—parsing, representation, chunking, indexing, retrieval, and evaluation—and offers practical engineering patterns with sample code.
1. The Core Problem: Why Heterogeneous Information Creates Retrieval Gaps
Traditional text embedding models map strings to dense vectors, and their semantic space is built on co-occurrence statistics of words and sentences. An image is a pixel matrix, and a table is a two-dimensional or even multi-dimensional cell structure. Neither shares the same representation space as text, so directly concatenating them or forcing a description introduces loss.
More specifically, the gap comes from three places. First, extraction loss: when layout analysis is poor, a table is flattened into an unstructured character sequence and the correspondence between headers and data disappears. Second, granularity mismatch: a table spanning multiple pages is split across several text chunks, and no single chunk carries complete semantics on its own. Third, inconsistent query form: users ask in natural language, while the target evidence is graphical or structured data, and without a bridging representation it is hard to match.
2. Parsing Layer: Restore the Layout Before Vectorizing
A high-quality vector store presupposes high-quality parsing. It is recommended to break document parsing into a four-step pipeline:
- Layout analysis: identify regions such as headings, body text, figure captions, table captions, headers, and footers, and output a sequence of blocks with coordinates;
- Region classification: distinguish real tables, pseudo-tables (text aligned with spaces), illustrations, and decorative graphics;
- Structure restoration: rebuild rows, columns, and merged-cell relationships for tables, and preserve the original resolution and positional context for images;
- Content normalization: unify encoding, remove repeated headers, fix broken lines, and form an intermediate representation with structural tags.
A sample intermediate structure is shown below. All subsequent embedding and chunking are based on it rather than on flattened text:
{"page": 12,"blocks": [{"type": "heading", "text": "Chapter 3 Rate Description"},{"type": "table", "bbox": [72, 210, 520, 430],"rows": [["Tier", "Monthly Usage", "Unit Price"], ["A", "<=100k", "0.12"]],"caption": "Table 3-2 Tiered Rates"},{"type": "figure", "bbox": [80, 460, 500, 700],"caption": "Figure 3-1 Request Pipeline Diagram"}]}
One point deserves emphasis in practice: parsing quality must be measurable. It is advisable to sample and manually annotate block types and table cell alignment accuracy, and to treat the parsing error rate as a gate metric for the ingestion pipeline, avoiding “garbage in, garbage out.”
3. Representation Layer: Three General Technical Routes
Route 1: Multimodal Embeddings, Placing Images and Text in One Vector Space
Multimodal embedding models use contrastive learning to align images and text into a unified space, so “the vector of an image” and “the vector of a sentence describing that image” sit close to each other. In the ingestion flow, an illustration can produce two kinds of vectors: a vector of the image itself, and a vector of its caption and surrounding context text. Both are written into the same collection, so a query in either modality can hit at retrieval time.
It is worth noting that the effectiveness of image-text alignment depends on the distribution of the training corpus, and it is often insufficient for strongly domain-specific images such as engineering drawings and medical images. In those cases, add Route 2 or Route 3 as a fallback.
Route 2: Text-Based Representation, Translating Non-Text into Embeddable Language
This is the most compatible and lowest-cost approach. Its core is to generate a “stand-in that a text model can understand” for non-text elements:
- Table linearization: expand in row-major order, keep the header, and concatenate row by row so the semantics stay complete;
- Structural markers: express hierarchy with explicit markers, for example “Header: Tier / Monthly Usage / Unit Price; Row 1: A / <=100k / 0.12”;
- Visual description: use a vision-language model to generate an objective description of an image, including text in the image, the meaning of the axes, and trend conclusions;
- Context injection: write the figure caption, table caption, and surrounding paragraphs together to fill in referential relationships.
def linearize_table(header, rows):cols = " / ".join(header)lines = [f"Header: {cols}"]for i, r in enumerate(rows, 1):cells = " / ".join(str(c) for c in r)lines.append(f"Row {i}: {cells}")return "\n".join(lines)def figure_to_text(caption, ocr_text, vlm_desc, context):return f"Caption: {caption}\nText in image: {ocr_text}\nVisual description: {vlm_desc}\nContext: {context}"
Route 3: Structured Summaries and Field-Level Indexing
For numerically dense tables, you can additionally generate statistical summaries (such as per-column totals, extremes, and year-over-year changes) and extract key fields as filterable metadata, for example reporting period, product model, and region. This way vector retrieval handles semantic similarity while metadata filtering handles exact conditions, and combining the two significantly reduces wrong recalls such as “similar but the wrong year.”
4. Chunking Layer: Use Semantic Completeness as the Boundary
The chunking strategy should follow content type rather than a fixed character count:
- Tables: use the whole table as the smallest unit and never cut across a table; for oversized tables, chunk by “repeat header + row groups” so every chunk carries its own header;
- Images: treat “image + caption + adjacent explanatory paragraph” as one chunk to avoid separating image from text;
- Body text: recursively split by heading hierarchy, keeping a small overlap between chunks to preserve references;
- Cross-page elements: merge first, then chunk, to prevent a cross-page table from being split in half.
A practical rule of thumb: if any single chunk, handed to an LLM on its own, cannot answer questions about itself without relying on other chunks, the chunking has crossed the boundary.
5. Indexing and Retrieval: Run Multiple Paths in Parallel, Then Fuse
A recommended index design keeps multiple collections side by side: a text chunk collection, a figure text-description collection, a table linearization collection, and an image vector collection. Each maintains its own vector index, and all attach unified metadata (document ID, page number, block coordinates, content type, effective date).
At retrieval time, run multi-path search, fuse and rerank the results, then send them to a reranking model for fine ordering. A sample flow:
def hybrid_retrieve(query, top_k=8):text_hits = vector_search(text_collection, query, top_k)table_hits = vector_search(table_collection, query, top_k)image_hits = vector_search(image_collection, query, top_k)merged = fuse_by_score(text_hits + table_hits + image_hits)merged = apply_metadata_filter(merged, must={"effective_date": "2025"})return rerank(query, merged)[:top_k]
On the generation side, add “citation back-referencing”: mark in the answer which page, which table, and which figure the evidence comes from, and provide the original image or table fragment to the model along with the context. This can greatly reduce hallucinations about numbers and legends.
6. Evaluation and Operations: Make Results Regressable
Non-text retrieval must be evaluated separately, otherwise overall metrics will mask the problems. It is recommended to build three kinds of QA sets: table-numeric, figure-trend, and joint image-text reasoning, and to measure hit rate and answer accuracy for each. In production, monitor parsing failure rate, empty-recall rate, and reranking position changes, and run sampling checks on newly ingested documents.
In terms of deployment, parsing and embedding are compute-intensive stages and can scale elastically on a container platform; original documents and intermediate artifacts are stored in object storage; task flow is decoupled with a message queue; and runtime status is observed through logging services and a monitoring and alerting system. In these kinds of scenarios, Baidu AI Cloud is typically used by combining the general categories above rather than relying on a single point capability.
Conclusion
Images and tables are not appendages of RAG; they are often the only source of an answer. A workable approach is to treat them as first-class citizens: restore structure at the parsing stage, choose multimodal embeddings or text-based stand-ins at the representation stage, hold the semantic boundary at the chunking stage, run multiple collections in parallel with metadata filtering at the indexing stage, and keep regressing with category-specific evaluation. Building along this chain allows the vector database to truly cover all the information in a document, and the retrieval gap is filled in the process.
