Zero Labs
Industry News / AI

Hybrid Search Starts with Two Good Candidate Lists

Source · Towards AI By James Luan

From the publisher’s feed, collected in the ZeroLabs newsroom.

Consider a support query containing both an error code and an ordinary description of what went wrong. Exact matching helps find the code. Semantic retrieval helps when the description uses different words from the documentation. Neither signal is sufficient simply because it works well on a different kind of request. The useful question is which evidence each retrieval path contributes.I would resist starting this discussion with a fusion formula. Combining two rankings cannot recover a document that neither path retrieved. It can also make a poor candidate set look more sophisticated without improving its coverage. Before tuning a hybrid result, I want to see the dense and lexical lists separately and understand their failures.Stefan Webb’s Milvus hybrid-search tutorial provides the implementation foundation: a dense field, a server-generated BM25 field, and reciprocal-rank fusion. The walkthrough below uses a small original support corpus to make those relationships inspectable. It builds on the Milvus 2.5 API pattern and should be run against a compatible Standalone or Distributed server, using a client version matched to that server.Give each representation a clear ownerThe application generates dense embeddings. Milvus generates the BM25 representation from the text field through a schema function. Keeping those responsibilities explicit helps prevent a common category mistake: treating the sparse output as another application-supplied embedding array. The input to the lexical branch is raw text, and the server’s analyzer participates in defining how that text becomes searchable.Install the matching PyMilvus client with its model dependencies, start a test server at the endpoint below, and run the five snippets in order in one Python session. The embedding model may download files on first use. The default endpoint is for a local experiment; supply the authentication and connection settings appropriate to your deployment. These are demonstration documents, not production evaluation data.from pymilvus import (MilvusClient, DataType, Function, FunctionType, AnnSearchRequest, RRFRanker, model)client = MilvusClient(uri="http://localhost:19530")collection = "james_hybrid_support_demo"encoder = model.DefaultEmbeddingFunction()documents = [ "ERR_AUTH_401 means the API credential is missing or expired.", "Rotate an expired API token in account settings before retrying.", "ERR_RATE_429 indicates too many requests; use bounded retry backoff.", "A network timeout does not prove that the server rejected a write.",]vectors = encoder.encode_documents(documents)dimension = len(vectors[0])if client.has_collection(collection): raise RuntimeError("Use a fresh demo collection name; existing data is preserved.")Deriving the field dimension from the actual model output avoids copying a number that belongs to a different encoder. I would still record the model identity and revision in a real system. Dimension compatibility is necessary, but it does not establish that document vectors and query vectors inhabit the same semantic space. Both sides must use the intended encoding pipeline.Connect text to BM25 in the schemaThe schema keeps source text alongside the dense representation. The text field enables analysis, and a BM25 function connects it to the sparse output field. That is the relationship I want visible in code review: which input feeds which derived field, and which system maintains that derivation when the source changes.schema = client.create_schema(auto_id=False, enable_dynamic_field=False)schema.add_field("id", DataType.INT64, is_primary=True)schema.add_field("text", DataType.VARCHAR, max_length=4096, enable_analyzer=True)schema.add_field("dense", DataType.FLOAT_VECTOR, dim=dimension)schema.add_field("sparse", DataType.SPARSE_FLOAT_VECTOR)schema.add_function(Function(name="support_bm25", input_field_names=["text"], output_field_names=["sparse"], function_type=FunctionType.BM25))An analyzer deserves testing rather than a casual default selection. Error identifiers, punctuation, product names, and multilingual content can expose differences between the text a person sees and the tokens a lexical index uses. A collection that accepts the data successfully can still behave unexpectedly on the precise identifiers that motivated adding full-text search.I would keep small analyzer-focused cases alongside broader relevance judgments. For example, check whether a request for a particular error identifier surfaces the document that explains it. That is a different question from whether a natural-language paraphrase retrieves a useful answer. Separating the cases makes it easier to decide whether a failure belongs to tokenization, dense encoding, or ranking.Build and populate both retrieval pathsEach vector field needs an appropriate index and metric. The dense path below uses cosine similarity; the lexical path uses BM25 with a sparse inverted index. These are separate score systems. Their numeric outputs should not be treated as though one unit of cosine similarity means the same thing as one unit of BM25 relevance.indexes = client.prepare_index_params()indexes.add_index(field_name="dense", index_type="AUTOINDEX", metric_type="COSINE")indexes.add_index(field_name="sparse", index_type="SPARSE_INVERTED_INDEX", metric_type="BM25")client.create_collection(collection, schema=schema, index_params=indexes, consistency_level="Strong")client.insert(collection, data=[ {"id": i, "text": text, "dense": vector.tolist()} for i, (text, vector) in enumerate(zip(documents, vectors))])client.flush(collection)client.load_collection(collection)Only the source text and dense vector are supplied during insertion. The schema function produces the sparse representation. The fixed IDs in this demonstration make returned results easy to compare. In a larger system, I would use stable identifiers that let evaluation reports connect a result back to its source document and current version.Changes to source text require careful ingestion behavior. A server-managed BM25 representation does not relieve the application of updating its dense embedding when the text changes. One database can store both fields while those fields still reflect different revisions if the application sends inconsistent updates. I would test that synchronization before trusting a hybrid result as a coherent view of a document.Inspect candidates before judging fusionChoose a query that can exercise both mechanisms, then request more candidates from each branch than the final output needs. Here the corpus contains only four records, so a candidate limit of four is enough to inspect the complete toy result. A production candidate budget needs measurement against corpus size, filtering, and latency constraints rather than being copied from this example.query = "How do I fix ERR_AUTH_401 after my access token expires?"query_vectors = encoder.encode_queries([query]).tolist()dense_candidates = client.search( collection, anns_field="dense", data=query_vectors, limit=4, search_params={"metric_type": "COSINE", "params": {}}, output_fields=["text"])lexical_candidates = client.search( collection, anns_field="sparse", data=[query], limit=4, search_params={"metric_type": "BM25", "params": {}}, output_fields=["text"])for label, results in [("dense", dense_candidates), ("BM25", lexical_candidates)]: print(label, [(hit["id"], hit["entity"]["text"]) for hit in results[0]])The raw query goes to the BM25 field, while the encoded query goes to the dense field. That difference is easy to obscure behind a helper function, but it matters when diagnosing results. I would keep both lists in evaluation artifacts, even if the application ultimately shows only the fused output.No particular ordering is promised by this walkthrough. Model behavior, analyzer settings, and the deployed version can affect it. The useful exercise is to identify which relevant records appear in each candidate set and which are absent from both. If a needed document never becomes a candidate, changing the final ranker’s preference is the wrong place to start repairing the failure.Fuse ranks and preserve the evidenceReciprocal-rank fusion combines positions in ranked lists rather than directly adding their raw similarity scores. That makes it a practical starting point when the branches use different metrics. It still requires judgment about candidate depth and the final result budget. A rank-based method is a baseline to evaluate, not a guarantee that every combined result improves.dense_request = AnnSearchRequest( data=query_vectors, anns_field="dense", param={"metric_type": "COSINE", "params": {}}, limit=4)lexical_request = AnnSearchRequest( data=[query], anns_field="sparse", param={"metric_type": "BM25", "params": {}}, limit=4)combined = client.hybrid_search( collection, reqs=[dense_request, lexical_request], ranker=RRFRanker(), limit=3, output_fields=["text"])for hit in combined[0]: print(hit["id"], hit["entity"]["text"])I would compare this output with both standalone baselines on exactly the same requests. Preserve returned IDs and relevance judgments so disagreements can be inspected later. A hybrid system that improves one query class while harming another should make that tradeoff visible. One averaged success figure can conceal a regression in the requests that matter most to the application.Filtering needs the same discipline. If tenant or access restrictions apply, both retrieval branches must operate within the intended authorized scope. The small public toy corpus omits those requirements for clarity. They belong in a production design before relevance tuning, because retrieving an unauthorized candidate is not an acceptable intermediate step simply because a later stage might remove it.Evaluate the retrieval system you intend to shipI would build an evaluation set containing exact identifiers, natural-language paraphrases, ambiguous requests, and queries with no useful answer in the corpus. Measure candidate coverage and final ranking quality, then inspect per-query differences. A small demo proves the API wiring; it cannot establish the business value of hybrid retrieval or justify a general claim about recall improvement.Latency and operational behavior belong beside relevance. The two branches share a request budget, and the service needs a deliberate response when retrieval fails or times out. If an application introduces a fallback, record when that fallback runs. Otherwise a system described as hybrid may often be serving a different retrieval path without its operators noticing.The full-text search documentation and multi-vector search guide explain the relevant API mechanisms. My starting point is narrower: create two understandable candidate lists, preserve their evidence, and test whether fusion helps the actual workload. The additional machinery earns its place when those results support it, not merely when the final call returns successfully.Hybrid Search Starts with Two Good Candidate Lists was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.