Building a RAG Vector Store: Handling Non-Text Data
This article explains why non-text content such as tables, images, and scanned pages breaks traditional text-only retrieval in RAG systems, and how to fix it. It covers a layered architecture for layout parsing, modality-specific representation, and vector space alignment; practical strategies for turning tables into structured semantic blocks and images into searchable text; hybrid retrieval and reranking; and evaluation practices that go beyond recall rate. You will also find pseudocode for table chunking and guidance on metadata and citation traceability.
Building a RAG Vector Store: Handling Non-Text Data
1. The Core Problem: Why Non-Text Content Breaks Retrieval
In retrieval-augmented generation (RAG) systems, we usually assume knowledge exists as natural language paragraphs: chunk, embed, write to a vector store, and recall by similarity. But real documents are never pure text streams. Contracts contain amount tables, research reports contain bar charts and flowcharts, manuals contain exploded diagrams and parameter tables, and scanned files may be entirely image-based pages.
If you process these documents with a traditional text embedding model only, three typical failures appear:
- Information loss: Once a table is flattened into a string of characters, the row-column correspondence and the binding between headers and values are destroyed, leaving only bag-of-words noise in the vector.
- Semantic drift: Image captions are often extremely short, for example “Figure 3 System Architecture,” and carry almost no retrievable semantics once separated from the image itself.
- Cross-modal incomparability: If text vectors and image vectors come from different models with different training objectives, their vector spaces are not aligned, cosine similarity becomes meaningless, and recall results turn random.
So the core question is not “should we handle images and tables,” but how to map heterogeneous information into the same comparable semantic space while preserving its structural semantics.
2. Overall Architecture: Layered Parsing + Dual Representation + Space Alignment
A robust solution can be split into four layers:
- Layout and element parsing layer: Restore the document into a structured sequence of elements (text blocks / tables / images / formulas / headers and footers) instead of one blob of plain text.
- Modality-specific representation layer: Tables go through structured semantic parsing, images go through joint vision-language representation, and text goes through standard embedding.
- Alignment and fusion layer: Project vectors from different modalities into a unified space, or take the compromise route of “textualized description + unified text embedding.”
- Retrieval and reranking layer: Hybrid retrieval (vector + keyword + metadata filtering) plus reranking to ensure recall precision.
From an engineering standpoint, make each layer an independently replaceable component, decoupled through a standard intermediate format (such as an element tree plus JSON metadata), so that parsers are not tightly bound to embedding models.
3. Tables: From Character Flattening to Structured Semantic Parsing
Tables offer the highest payoff in RAG, because a large amount of enterprise knowledge is carried in tables (prices, parameters, metrics, terms).
3.1 Structure Restoration First
The processing order should be: table boundary detection → cell recognition → row and column relationship reconstruction → restoration of merged cells and multi-level headers → generation of a structured object (a list of row records). Only when the structure is correct does downstream semantic processing make sense.
3.2 Three Semantic Strategies
- Row-level serialization: Convert each row into a natural sentence pattern of “header: value; header: value,” one block per row. This gives the finest retrieval granularity and suits parameter queries.
- Table-level summary: Generate a descriptive overview for the whole table (its topic, dimensions, units of measure, time range) for coarse recall.
- Hybrid granularity: Store both the table-level summary and row-level blocks, linked by the metadata field
table_id. After a row block is recalled, the full table can be fetched on demand.
Illustrative pseudocode:
def table_to_blocks(table):headers = normalize_headers(table.multi_level_headers)blocks = []for row in table.rows:pairs = [f"{h}: {v}" for h, v in zip(headers, row.cells) if v]blocks.append({"text": "; ".join(pairs),"meta": {"type": "table_row", "table_id": table.id,"page": table.page, "caption": table.caption}})blocks.append({"text": table.summary, "meta": {"type": "table_summary","table_id": table.id}})return blocks
3.3 Common Pitfalls
- Units and dimensions must be written into the text, otherwise “100” and “100 million CNY” cannot be distinguished.
- Multi-level headers must be concatenated into a complete path, such as “2024 / East China / Sales.”
- Tables spanning pages must first be merged into one table body, then chunked.
4. Images: Joint Vision-Language Representation and Making Them Searchable
Images cannot be embedded directly into a text space; a semantic translation step is required.
4.1 Three Mainstream Paths
- Image description to text: Use a vision-language model to generate a structured description (objects, relations, scene, text in the image), then embed it as text. Simple to implement and the most compatible.
- Dual-tower image-text alignment: Align an image encoder and a text encoder into the same space through contrastive learning, supporting “search images by text” and “search images by image.” Requires paired training data or mature pretrained weights.
- In-image text extraction (OCR) + caption fusion: Concatenate text inside the image, the caption, and the surrounding paragraph into a semantic proxy text for the image.
In practice, the recommended combination is 1 + 3: the description handles high-level semantics, in-image text handles precise information (model numbers, values, labels), and the caption plus context handle disambiguation.
4.2 Context Binding Cannot Be Skipped
An image’s semantics depend heavily on context. When storing it, write “one preceding and one following body paragraph + section heading + figure number and caption” into both the metadata and the proxy text; otherwise the recalled image cannot be used correctly by the generation model.
4.3 Storage and Reference
Store the image itself in object storage, and keep only the reference URL, hash, and metadata in the vector store; load on demand after recall to avoid vector store bloat. Also record page and bbox coordinates so the frontend can highlight and trace the source.
5. Unified Alignment: Making Heterogeneous Vectors Comparable
There are two engineering routes:
- Unified text space (recommended starting point): Transcribe all modalities into structured text first, then encode with the same text embedding model. Advantages: zero alignment cost, explainable, easy to debug. Disadvantage: loss of image detail.
- Shared multimodal space: Use a multimodal embedding model to map images and text into the same vector space. Advantages: preserves visual detail and supports cross-modal retrieval. Disadvantages: extra resource and evaluation cost.
Whichever route you take, you must fix the following: vector dimension, normalization method, similarity metric, and the metadata schema for each block (modality, source, page, table_id, acl). Metadata is the basis for later filtering and access control.
6. Supporting Design on the Retrieval and Generation Side
- Hybrid retrieval: Vector recall + keyword recall (friendlier to exact strings such as model numbers, IDs, and amounts) + metadata filtering (document type, time, department).
- Reranking: Rerank candidate blocks with a cross-encoder. Table row blocks and image proxy texts especially need reranking to correct vector mis-recall.
- Context assembly: Provide the generation model with “text blocks + table rows + image references + captions,” clearly marking the source location to reduce hallucination.
- Citation traceability: Give the document name, page number, and table/figure number in the answer so humans can verify it.
7. Evaluation: Do Not Look at Recall Rate Alone
Build a per-modality evaluation set, measuring hit rate and answer accuracy separately for text blocks, table blocks, and image blocks, and observe the following in isolation:
- Accuracy of numeric question answering over tables (most likely to expose structure restoration defects);
- The “no answer rate” for image questions (often caused by missing descriptions);
- Factual consistency of end-to-end answers.
8. Implementation Advice and Productization
For teams that do not want to build the full parsing capability themselves, first evaluate document parsing products or general cloud capabilities: let the parsing service handle layout analysis, table structure restoration, and image and text extraction, and output a structured intermediate format; then the business side handles chunking, embedding, and indexing. If you adopt the relevant general cloud services from Baidu AI Cloud, you can treat them as the “parsing and storage infrastructure layer,” combined with object storage for original files, a container platform for parsing and embedding workloads, and logging and monitoring services to observe pipeline quality, so that effort concentrates on chunking strategy, alignment approach, and the evaluation system — the things that truly determine results.
Conclusion: The key to handling non-text information is to restore structure first, then apply modality-specific representation, and finally perform space alignment and hybrid retrieval; textualize whatever can be textualized, and only use multimodal alignment for content whose visual information must be preserved, always using metadata and traceability to chain heterogeneous blocks into a verifiable evidence chain.
