Hybrid Search and Retrieval#
RAGFlow's retrieval pipeline combines BM25 full-text scoring with KNN vector scoring to produce a single ranked result set. The pipeline is implemented in two stacks: a Python stack centered on the Dealer class in rag/nlp/search.py , and a Go stack exposing the same semantics through RetrievalService in internal/service/nlp/retrieval.go . Both stacks support Elasticsearch/OpenSearch and Infinity backends.
Mode Selection#
Search mode is chosen at query time based on whether an embedding model is available :
| Condition | Mode |
|---|---|
EmbeddingModel == nil | Text-only (BM25) โ only a MatchTextExpr is sent to the engine |
EmbeddingModel present, VectorOnly == false | Hybrid โ [MatchTextExpr, MatchDenseExpr, FusionExpr("weighted_sum")] |
VectorOnly == true | Dense-only โ only MatchDenseExpr is sent; no BM25 clause or fusion step |
The VectorOnly flag is used when callers need to bridge a wording gap where the query's own words are not reliable signals . When VectorOnly is set and VectorSimilarityWeight is not explicitly provided, it defaults to 1.0 rather than the standard 0.3 so that token coincidence does not re-rank a pure-vector result set .
For the OpenSearch backend, hybrid mode additionally requires the normalization pipeline to be active. _init_hybrid_search() provisions a ragflow_hybrid_pipeline at startup; if the server is below v2.10 or provisioning fails, the backend silently degrades to vector-only KNN .
Query Construction#
Three expression types drive the hybrid query :
MatchTextExprโ fields, BM25 query string, top-N, andminimum_should_match. The query string is built byQueryBuilder.Question(), which tokenizes the text, computes term weights, expands synonyms, and adds phrase and proximity clauses .minimum_should_matchmirrors Python:0.3by default, dropping to0.0whenvector_similarity_weight >= 0.8.MatchDenseExprโ vector column name (q_{dim}_vec, wheredimis the embedding model's output dimension), cosine distance metric, top-N, and asimilarityfloor. The query vector is embedded via the model's asymmetric query encoding .FusionExprโ method"weighted_sum", top-N, and weights. For Infinity, weights are"{termWeight},{vectorWeight}"derived fromVectorSimilarityWeight. For Elasticsearch/OpenSearch, a fixed"0.001,1"pair is sent โ the actualVectorSimilarityWeightis applied afterward during reranking .
The query fields searched by MatchTextExpr are :
title_tks^10, title_sm_tks^5, important_kwd^30, important_tks^20,
question_tks^20, content_ltks^2, content_sm_ltks
Scoring and Reranking#
After the backend returns candidates, the Go scoreSearchResult() (and its Python equivalent in Dealer.retrieval()) applies one of four reranking paths :
RerankByModel()โ if a rerank model is configured, uses a cross-encoder; normalizes provider scores before blendingtkWeight * tsim + vtWeight * modelSim.RerankWithKNN()โ default ES/OpenSearch path: issues a second KNN-only pass (KNNScores) against the candidate set to recover clean cosine scores, then blends with local term similarity .RerankStandard()โ OceanBase path; fetches stored chunk vectors and computes cosine similarity locally .- Infinity passthrough โ uses the engine's own normalized fusion score directly (
_score,SCORE, orSIMILARITYfield) without an application-side reranking pass .
The composite score formula is sim = tkWeight * tsim + vtWeight * vsim, where tkWeight = 1 - VectorSimilarityWeight and vtWeight = VectorSimilarityWeight .
Fallback Behavior on Empty Results#
When the initial search returns zero hits :
- Standard hybrid โ retries with a lower
min_match(0.1vs.0.3) and relaxed vector similarity floor (0.17). - Dense-only /
VectorOnlyโ retries with the similarity floor reduced to0.17. - Doc-IDโscoped search โ falls back to a filter-only query (no match or vector expressions) to return any chunks matching the metadata filter.
- After all retries, if still empty and
AllowDenseFallbackis true, a final dense-only search at0.17similarity is attempted.
Configuration Reference#
Key RetrievalRequest parameters and their defaults :
| Parameter | Default | Effect |
|---|---|---|
SimilarityThreshold | 0.2 | Minimum composite score to include a chunk. Bypassed (set to 0.0) when VectorSimilarityWeight <= 0 or VectorOnly == true. |
VectorSimilarityWeight | 0.3 (hybrid), 1.0 (VectorOnly) | KNN weight; 1 - this is the BM25/term weight. |
KNNTopK | 1024 | Maximum candidates fetched from the KNN leg. |
KNNNumCandidates | 2048 | ANN candidate pool size. |
RerankCandidatesCount | 64 | Candidate pool for the reranking pass. |
RerankModel | nil | If set, activates cross-encoder reranking. Pagination is only supported when nil. |
AllowDenseFallback | true | Enables the dense-only fallback search when hybrid returns no results. |
For OpenSearch, the hybrid pipeline name defaults to ragflow_hybrid_pipeline and can be overridden via the OS_HYBRID_PIPELINE environment variable. Default leg weights are [0.5, 0.5] .
Key Source Files#
| File | Purpose |
|---|---|
internal/service/nlp/retrieval.go | Go RetrievalService โ full hybrid pipeline, fallback logic, scoring dispatch |
internal/service/nlp/query_builder.go | QueryBuilder.Question() โ BM25 query construction, tokenization, synonym expansion |
rag/nlp/search.py | Python Dealer class โ search, retrieval, reranking (reference implementation) |
rag/utils/opensearch_conn.py | OSConnection โ OpenSearch hybrid pipeline provisioning, DSL builder |
internal/engine/infinity/chunk.go | Infinity backend chunk handling and fusion score extraction |