Vectorizing Images and Tables in LLM RAG Pipelines
This article explains how to treat tables and images as first-class retrieval evidence in RAG, covering layout recovery, structured representations, multi-field indexing, hybrid recall, and traceable generation—without flattening everything into plain text.
Vectorizing Images and Tables in LLM RAG Pipelines
In retrieval-augmented generation, document ingestion is often reduced to extract text, split chunks, embed, and write to a vector store. That flow is workable for plain text. Once documents contain tables, images, flowcharts, scanned pages, formulas, and complex layouts, text-only extraction creates information gaps: row–column relationships collapse into hard-to-parse strings, visual meaning is lost, axes and legends never enter the retrieval space, and phrases such as “as shown in Table 2” or “see Figure 3” cannot be linked to the corresponding elements.
RAG quality depends not only on the generator but on whether retrieval can surface the evidence needed to answer. Handling images and tables is therefore not “add OCR.” It is a pipeline of multimodal parsing, structured representation, unified indexing, hybrid retrieval, and traceable generation.
1. Non-text elements are retrieval breakpoints, not extras
Tables carry multidimensional metrics, comparisons, statistics, and parameter matrices. Images carry process, structure, trends, diagrams, and scans. Text-only embeddings typically fail in four ways.
First, table structure is lost. A table includes name, caption, headers, merged cells, units, footnotes, totals, and data rows. Concatenating the whole table weakens column–value alignment, multi-level headers are misjoined, and units may be dropped. A query such as “what is the annual growth rate of product X in region Y” needs a specific row, column, and time—not a paragraph that happens to contain numbers.
Second, visual semantics never enter the text vector space. A line chart may encode trend, inflection, legend, units, and outliers; an architecture diagram encodes nodes, arrows, and hierarchy; a scan may mix text, stamps, and signatures. Filenames or short captions cannot support queries like “which step performs authorization” or “what trend does this chart show.”
Third, hierarchy and cross-references break. Technical docs, policies, research reports, and manuals use chapters, figure numbers, footnotes, and citations. Chunks without chapter path, caption, neighboring text, and page number leave the generator without context for evidence.
Fourth, OCR is not retrievable meaning. OCR extracts characters but does not restore reading order, header hierarchy, legend mapping, or visual structure. OCR-then-chunk still yields misaligned columns, misplaced captions, and header/footer pollution.
The goal is retrievable, explainable, traceable, verifiable representations so text, tables, and images work in one retrieval framework—not compression of everything into ordinary prose.
2. Architecture: from parse to multimodal vectorization
A complete pipeline can be described in seven layers.
- Ingest and versioning: Keep the original file, document ID, version, hash, source, permissions, and update time. Parsed results, image crops, and table structures should trace to original pages and coordinates.
- Layout analysis and structure recovery: Detect titles, paragraphs, lists, headers/footers, footnotes, tables, images, formulas, stamps, and scan regions; restore reading order; keep page numbers and bounding boxes. Scans need OCR; complex layouts need multi-column vs. figure regions distinguished.
- Element-level semantic normalization: Organize text by section; restore table rows/columns and units; produce structured image descriptions; convert formulas to readable form; normalize dates, amounts, percentages, and place names.
- Multi-granularity chunks and parent–child links: Document → section → paragraph or element; table → row groups; image → caption. Hits at row or figure level can expand to the parent section and context.
- Multiple representations: Summary, structured payload, keywords, OCR, and captions. Images may add visual embeddings; tables may add row-level facts. Visual vectors are optional; textual descriptions and structured fields are baseline.
- Multi-field index and hybrid recall: Store embeddings plus metadata: element type, section path, page, column names, time range, units, entities, permissions, confidence—for semantic search, keyword search, exact filters, and structure queries.
- Retrieve, rerank, assemble context: Classify intent, recall from text/table/image indexes, fuse and rerank, pass original evidence plus structured data and context to the generator, and require citations.
Ingest flow in pseudocode:
for document in documents:parsed = parse_document(document)elements = recover_layout_and_reading_order(parsed)for element in elements:if element.type == "text":text_chunks = structure_aware_chunk(element)index(text_chunks)elif element.type == "table":table = normalize_table(element)row_groups = semantic_row_grouping(table)summary = summarize_table_structure(table)index(table_summary=summary, rows=row_groups, raw=element)elif element.type == "image":ocr_text = optional_ocr(element.crop)context = caption_and_neighbor_text(element)description = structured_image_description(element.crop, context)index(image_summary=description, ocr=ocr_text, raw=element)link_cross_references(document)propagate_permissions_and_versions(document)
3. Tables: structure recovery, semantic parsing, multi-granularity index
Do not stop at “table as a string.” Recover structure, normalize semantics, chunk at multiple grains, and retrieve on multiple paths.
3.1 Recover native structure before embedding
Keep table name, caption, header hierarchy, merged cells, units, footnotes, data rows, totals, and source. Expand multi-level headers into paths (for example, Revenue → Core business → East China), not only the leaf column name. Propagate merged cells onto data rows or express them by reference. Type-mark percentages, amounts, dates, ranges, and missing values so “120 million yuan” and “12,000 ten-thousand yuan” are not treated as unrelated concepts.
Retain location: page, bounding box, section, neighboring paragraphs, and figure/table numbers. Row-level retrieval and structured filters only work if structure is reliable.
3.2 Three-layer representation: summary, schema, row records
Generate a table-level summary, a schema for columns/headers, and retrievable row records.
The summary answers “which table might contain the answer”: topic, audience, main dimensions, metric scope, time range, units, and constraints. Example: “This table describes operating revenue and year-over-year growth by region and year; amounts are in ten-thousand yuan.”
Schema describes column meaning: names, units, data types, enumerations, comparability, whether a row is a total. Row records support precise retrieval, e.g. table–entity–dimension–metric–value–unit–time. Wide tables can use object–attribute–value facts; statistical tables should keep row-group × header combinations so numbers are not isolated.
3.3 Chunking: retrieval grain vs. context
Small tables: whole table as parent, rows as children. Large tables: group by business dimension; each row group repeats table name, header path, and units. Mark totals, averages, and subtotals so they do not mix with ordinary row retrieval. Merge cross-page tables before chunking; keep worksheet names in multi-sheet files.
Retrieval can be “recall table, then expand rows”: find the table via the summary, match rows and apply structured filters, then show only needed rows and headers to the model—shorter context and fewer numeric mismatches.
3.4 Combine semantic, keyword, and structured filters
Table questions mix meaning and exact conditions, e.g. “which products in East China had gross margin above 20% in the last three years.” Vector similarity is not enough: match table/column names, exact entities, time filters, unit normalization, and numeric ranges, then rerank by query–schema fit.
At generation time, pass caption, headers, units, selected rows, and source, and require citation of table and page. For aggregation, sort, or comparison, prefer structured query or precomputation, then let the model phrase the result—not mental arithmetic over raw digits.
3.5 Quality pitfalls
Skewed scans misalign cells; merged headers break; footnotes become data rows; totals mix with detail; units are inconsistent; cross-page tables stay unmerged; in-cell formulas or comments drop; empty cells are ambiguous. Keep parse confidence, sample high-risk tables, and instruct the model to answer only from visible table content and to state missing fields.
4. Images and charts: from pixels to retrievable meaning
Classify first, then choose representation. Information density and query types differ by image class.
4.1 Type-specific handling
Scanned text: OCR plus layout; keep paragraph order and region coordinates. Line, bar, and pie charts: axes, legend, labels, trend, outliers; if underlying data can be extracted, store it; otherwise keep a structured description and note that visual readings may be inexact. Flow and architecture diagrams: nodes, arrows, hierarchy, and relations (e.g. request → gateway → auth → retrieval). Photos: scene, entities, attributes, spatial relations. Formulas: readable form plus symbol definitions. Filter decorative icons and page logos so they do not pollute retrieval.
4.2 Captions, neighbors, and OCR as context
Captions are too coarse alone. Include caption, previous/next paragraph, section title, and in-body cross-references. For scans, OCR is primary evidence; for charts, legend and axis text; for flowcharts, node labels and edges. Keep source coordinates so content from different figures is not concatenated.
4.3 Structured visual descriptions, not a single vague summary
Describe type, visible elements, relations, text labels, axes, legend, time range, trends, anomalies, and uncertainties. Ground claims in what is visible; do not invent numbers or labels. Distinguish labeled values from trend summaries; emit node/edge lists for architecture diagrams; keep OCR text and reading order for scans.
Index description, OCR, caption, and neighboring text separately so a query like “which module in Figure 3 handles authorization” can hit node labels, image description, or section context. Cross-modal visual vectors are optional; mapping structured descriptions into a shared text embedding space is often easier to ship and evaluate.
4.4 Risks and controls
Vision models can hallucinate plausible but absent content. Require descriptions to cite only verifiable elements; flag OCR vs. visual-summary conflicts; prefer original tables or OCR for exact numbers; keep original-image links and page numbers for human traceability; redact faces, IDs, seals, and sensitive content and enforce permissions. Descriptions are a recall and explanation aid, not a replacement for the original image.
5. Unified data model for joint retrieval
Each retrievable element should include at least: element ID, document ID, version, type, parent ID, section path, page, bounding box, original resource URI, title/caption, content summary, structured payload, vector fields, keyword fields, metadata, permissions, source hash, and parse confidence.
A table may have summary vectors, row-record vectors, and column-name keywords. An image may have caption, OCR, visual-description, and neighbor-text vectors. A paragraph has body and section-context vectors. Index fields separately and fuse at query time. Parent–child links expand context; cross-reference links resolve “see Figure 3” / “as in Table 2.”
Do not store tables as summaries only or images as one-line captions. Keep original element, structured form, and retrievable summary so the system can decide whether the question needs text, table, or image, and so the generator receives raw evidence.
6. Retrieval and generation: hybrid recall, rerank, citations
Rewrite and classify intent: fact lookup, numeric comparison, trend, process, or cross-figure reference. Extract entities, time, region, metrics, and figure/table numbers as filters. Recall from text, table, and image indexes.
Multi-path recall: dense retrieval for related paragraphs; sparse/keyword for proper nouns; metadata filters on section, time, permission, and type; row-level table match on metrics and entities; image match on caption, OCR, and visual description. Merge with weighted or rank fusion.
Rerank on semantic relevance, type match, verifiable evidence, whether table schema covers query dimensions, whether the image description contains the referred object, parse confidence, and section position. For “column X in Table 2,” figure number, page, and table name should weigh heavily; for “what is the trend,” caption, chart description, and raw data all participate.
Context assembly: keep original evidence, supply required headers and units, and cite sources. Prompt the model to prefer structured tables and OCR, to state the basis of visual trend claims, and to say when information is missing.
7. Engineering and quality
This is ongoing data engineering, not a one-off parse. Evaluation should cover real user questions: parse accuracy, row/column recovery, OCR quality, recall, citation correctness, numeric accuracy, and chart QA. High-risk documents need sampling review and confidence thresholds.
Cost: classify layouts first; call vision only on complex images; cache parses, crops, and descriptions. On updates, use stable IDs and idempotent writes; keep old versions for rollback and provenance. Inherit document permissions at element level, redact sensitive image content, and audit retrieval and access.
For high scan ratios, complex tables, and mixed layouts, document-parsing services (for example Baidu AI Cloud document parsing) can reduce OCR, layout, table reconstruction, and outline cost. Parsing is only one stage; structured storage, multi-field indexes, hybrid retrieval, and human sampling are still required. Parsed output is not automatically high-quality retrieval.
8. Implementation checklist
- Do not flatten tables into ordinary text; keep name, headers, units, row records, and page.
- Do not give images a single generic caption; combine caption, OCR, neighboring text, and structured visual summary.
- Keep original file, page, bounding box, and version for every element.
- Use parent–child chunking: retrieve small fragments, expand to section and original element at generation time.
- Index multiple fields: summary vectors, OCR, body, captions, keywords, structured metadata.
- Prefer structured filters and row match for table questions; do numeric work on the retrieval side when possible.
- Mark uncertainty on visual readings; prefer original tables or clear OCR for exact numbers.
- Use hybrid recall and rerank; do not let a single similarity score pick the full context.
- Evaluate table QA, chart QA, and cross-reference QA on real business questions; collect failures.
- Iterate parse, index, retrieve, generate, and permissions together—not a single model.
In short: when building a vector store from documents, treat images and tables with structure first, semantic enrichment, multi-path indexes, and traceable evidence. Do not force text, tables, and images into one content type. Keep distinct representations in a shared retrieval framework, aligned via multi-vector fields, structured metadata, and hybrid recall. Closing the loop among parse quality, index design, and generation constraints is what makes RAG reliable on questions that need table math, chart understanding, and cross-page references.
