Vector Retrieval System Reconstruction: From Image Search to Knowledge Q&A
This article explores the architectural evolution of vector retrieval systems from basic image similarity search to knowledge-based question-answering (Q&A). It details practical engineering approaches including boundary-driven data modeling, data processing quality control, distance metric and indexing trade-offs, hybrid retrieval with rank fusion, end-to-end pipeline design, recoverable incremental updates, and a layered metrics strategy for issue isolation.
I. Redefining Vector Retrieval: From Similarity Query to Evidence Acquisition
Early image similarity search applications typically featured a straightforward processing pipeline: convert images to vectors, store vectors and image identifiers, calculate similarity during queries, and return matching images. As business requirements expanded, simple similarity sorting became insufficient. Query results often needed to be constrained by business categories, exclude expired data, enforce access permissions, or rank items based on a combination of text descriptions and image content.
Knowledge Q&A scenarios further shifted the retrieval objective. The retrieval system is no longer just looking for visually or semantically similar items; it must provide reliable evidence for the generation process. Semantically similar text may not actually answer the question, and top-ranked content might be outdated, lack context, or be inaccessible.
Therefore, when reconstructing a vector retrieval system, the goal should shift from “being able to search” to “being able to stably acquire valid evidence.” This goal encompasses at least four aspects:
- Relevance: Whether the results address the user’s actual question.
- Completeness: Whether the results contain the necessary conditions, conclusions, and context required to answer.
- Validity: Whether the data is still applicable and if the version is correct.
- Controllability: Whether the retrieval results comply with permissions, latency, and resource constraints.
Vector retrieval is a crucial technology for achieving these goals, but it is not the complete solution itself.
II. Define Business Boundaries Before Designing Data Structures
1. Clarify Retrieval Objects and Return Units
The return unit for image retrieval is usually a single image, whereas for knowledge Q&A, it is typically a text snippet. The data granularity differs, and modeling methods should not be mechanically copied between the two.
For images, you can store the image ID, storage location, category, source, creation time, and vector. For documents, it is essential to distinguish between the “original document” and the “retrieval snippet”: the original document handles version management and source tracking, while the retrieval snippet handles matching and evidence provision.
This layered relationship helps solve two problems. First, multiple snippets from the same document can share permission and version information. Second, hitting a snippet allows tracing back to the complete chapter, preventing misunderstandings caused by viewing only a partial conclusion.
2. Treat Metadata as Part of Retrieval Capability
Beyond the vector field, it is recommended to design the following information based on business needs:
- Document ID and snippet ID;
- Business category, belonging space, and data source;
- Title, chapter path, and body snippet;
- Document version, update time, and validity status;
- Accessible scope;
- Vector generation version;
- Content checksum.
These fields should not be maximized unnecessarily. Fields used for filtering, sorting, or tracking should be stored structurally, while other information can reside in the raw content storage.
It is particularly crucial to distinguish between the document version and the vector generation version. Unchanged text does not mean the vector representation remains comparable; if the method for generating vectors changes, old and new vectors may no longer exist in a consistent representation space. Failing to record versions makes it extremely difficult to troubleshoot subsequent retrieval quality fluctuations.
III. Data Processing Quality Determines the Retrieval Quality Ceiling
1. Text Cleaning Must Go Beyond Character Deletion
Document cleaning should preserve business-relevant structures, such as heading hierarchies, list relationships, table fields, and the sequence of operational steps. Over-deleting formatting can sever the association between “condition-action-result.”
For scanned documents, pay close attention to OCR errors. Recognition deviations in numbers, units, negative words, and key symbols are often more dangerous than standard text errors. Content involving amounts, dates, or technical constraints should undergo stricter validation processes.
2. Chunking Should Prioritize Semantic Boundaries
Fixed-length splitting is simple to implement but easily fragments complete conclusions. A more sound approach is to first identify chapters, paragraphs, and list structures, and then combine content under length constraints.
Overlapping snippets can mitigate boundary information loss but will increase storage volume and duplicate recall. The overlap ratio should not be fixed empirically long-term; it should be validated against actual queries.
For tables, preserve the correspondence between column names and rows; for operation manuals, maintain step order and prerequisites; for policy documents, retain scope of application, exception clauses, and effective dates. Different content types require different splitting rules.
3. Deduplication Must Distinguish Between Duplicates and Version Differences
Completely duplicated content wastes index resources and occupies slots in retrieval results. However, similar content cannot always be deleted. For instance, new and old policies might share most text but have different effective dates.
Content checksums can be used to identify exact duplicates, while approximate duplicates can be handled by combining source, version, and status. During the retrieval phase, results can also be merged by document source to prevent multiple highly similar snippets from the same document from crowding out the context.
IV. Understanding Distance Metrics and Indexing Trade-offs
1. Distance Calculation Must Align with Vector Representation
Common vector comparison methods include Euclidean distance, inner product, and cosine similarity. Euclidean distance measures spatial position differences; the inner product is influenced by both direction and vector magnitude; cosine similarity focuses primarily on direction.
When choosing a metric, follow the requirements of the vector generation method rather than just relying on what is “more common.” If using unit-length normalized vectors, some sorting relationships can be converted, but this does not mean all metrics are equivalent in all scenarios.
The system must also clarify the score direction: for some, a smaller distance means higher relevance, while for others, a larger similarity means higher relevance. Confusing this during mixed ranking or threshold checks can lead to imperceptible errors.
2. Exact Search is an Important Evaluation Baseline
Exact search calculates the distance between the query and all vectors in the candidate set. It is suitable for smaller datasets and for establishing offline reference results.
Approximate search reduces the search scope through indexing, typically trading some recall loss for lower query costs. Judging whether approximate search is appropriate requires not only looking at response speed but also measuring its result coverage relative to exact search.
Note that vector neighbor recall rate and business relevance are different metrics. Even if an approximate index fully retrieves the nearest neighbors in the vector space, those results might not be the evidence the user’s question actually needs.
3. Index Types Should Match Resources and Update Methods
Common approaches include graph-based indexes, spatial partitioning indexes, and quantization indexes that reduce storage costs.
Graph-based indexes focus on adjacency relationships and search paths, requiring evaluation of memory consumption and build costs. Spatial partitioning methods first narrow the candidate scope before calculating distances, requiring attention to partition quality and query coverage. Quantization uses compressed representations to lower resource usage but may introduce distance estimation errors.
Actual selection should integrate data scale, vector dimension, update frequency, concurrency, and acceptable error margins. There is no universally optimal index independent of load conditions.
V. Why Knowledge Q&A Requires Hybrid Retrieval
1. Semantic Retrieval and Term Retrieval Solve Different Problems
Semantic retrieval excels at handling expression differences, such as when a user uses colloquial descriptions while the document uses formal terminology. Term retrieval is advantageous for exact matches of numbers, abbreviations, proper nouns, and explicit field values.
If a query includes a number that must be matched exactly, relying solely on semantic similarity might recall topically related content with a different number. Conversely, when users do not use the exact terms from the document, pure term matching might miss the correct evidence.
Therefore, both retrieval paths can generate candidates separately, followed by fusion.
2. Rank Fusion is Easier to Control Than Direct Addition
Raw scores from different retrieval paths usually do not share the same scale; directly adding them might allow one path to dominate the results long-term. A common method is to fuse based on result ranks:
fusion_score = sum(weight / (smoothing_constant + rank)) for each retrieval path.
The weights and smoothing constants here are design parameters that need to be determined through validation; no specific set of values should be treated as a universal optimum. After fusion, candidates can undergo fine re-ranking, focusing on whether the content actually answers the question rather than just being topically related.
3. Permission Constraints Cannot Be Left to the Generation Phase
Permissions must be validated before evidence enters the generation context. You cannot first feed inaccessible content to the generation process and then ask it not to leak it.
Filtering methods also affect recall. If you retrieve a small number of nearest neighbors first and then filter, results may be insufficient; if you pre-filter, you need to assess the impact of filter selectivity on index queries. The specific execution method depends on system capabilities, should be verified through actual testing, and should involve re-checking permissions and validity status for the final candidates.
VI. Establishing a Clear End-to-End Processing Pipeline
A maintainable knowledge Q&A system can be divided into the following stages:
Question Input -> Identity & Permission Confirmation -> Query Analysis -> Multi-way Candidate Retrieval -> Deduplication & Fusion -> Fine Re-ranking -> Evidence Organization -> Answer Generation -> Citation & Result Validation.
Query analysis does not mean rewriting every question. For precise number-based queries, keeping the original expression is often safer; for continuous questions with omitted subjects, it may be necessary to complete the retrieval intent using dialogue context.
Evidence organization should consider context capacity, source diversity, and information completeness. You cannot simply truncate the top-ranked snippets; instead, avoid duplicate content and preserve the association between conditions, conclusions, and sources.
When evidence is insufficient, conflicting, or outdated, the system should explicitly indicate uncertainty or guide the user to provide more information. The generation process cannot replace fact validation.
VII. Incremental Updates and Version Switching Require Recoverable Design
Business data changes continuously, and the update pipeline must cover additions, modifications, and deletions.
Adding data requires parsing, chunking, vector generation, and index writing. When modifying data, affected snippets should be identified to avoid unnecessarily rebuilding all content. Deleting data involves not just the original file, but also corresponding snippets, vectors, caches, and associated states.
The most common risk during updates is partial success. For example, if a new snippet is written but the old one is not yet invalidated, a query might see both versions simultaneously. To handle this, write the pending version first, confirm processing completion, and then switch the valid status. Whether atomic switching is supported depends on actual storage and retrieval capabilities; cross-component transactions should not be assumed by default.
When changing the vector generation method, a safer strategy is to build an independent new version index, switch the query path after offline evaluation and small-scale validation pass, and retain necessary rollback conditions.
VIII. Locate Issues with Layered Metrics Instead of Just Final Answers
1. Data Layer: Check Coverage and Quality
Focus on document parsing success rate, empty snippet count, duplication ratio, version consistency, and update delay. If key documents fail to enter the database correctly, no amount of complex sorting can fix it downstream.
2. Retrieval Layer: Check Evidence Hits
Build a test set containing real business questions and annotate the evidence capable of answering them. Evaluation should cover normal phrasing, colloquial rewrites, exact number queries, filtered queries, and questions with no answers.
Common observation metrics include the recall of relevant evidence, the precision of the top N results, the position of the first valid result, and source coverage. The test set should be split by business category to prevent overall averages from masking significant degradation in specific categories.
3. System Layer: Check Stability
Beyond average response time, pay attention to high-percentile latency, timeout ratios, resource consumption, and performance changes as concurrency grows. The test load should mimic real usage patterns rather than just repeating an easily cached query.
4. Answer Layer: Check Evidence and Consistency
Focus on whether the answer is supported by retrieved evidence, whether citations correspond to conclusions, whether restrictive conditions are omitted, and whether unsupported content is generated when evidence is insufficient. Only by separately recording retrieval failures and generation failures can you optimize effectively.
IX. Reducing Implementation Risk Through Progressive Reconstruction
Reconstruction does not require replacing all components at once. You can retain the existing pipeline first, adding data version fields, retrieval logs, and test sets; then optimize chunking and filtering; later introduce hybrid retrieval and fine re-ranking; and finally handle index switching and capacity planning.
Each stage should have clear acceptance criteria. For example, can sources be tracked after data structure adjustments? Did modifying splitting rules improve valid evidence hits? Does the index change meet recall and latency requirements? Can you reliably roll back after version switching?
The value of a vector retrieval system lies not in how many features are stacked, but in forming an explainable closed loop among data, retrieval, and business goals. Transitioning from image similarity search to knowledge Q&A truly requires upgrading engineering methods: placing similarity computation back into a complete framework of data governance, permission control, performance evaluation, and operational maintenance to achieve sustainable, reliable retrieval capabilities.
