Milvus Hybrid Retrieval Guide: BM25, Vectors and Reranking
Python 实战检索优化:BM25、向量与重排
The non-obvious point is that BM25 sparse vectors are generated inside Milvus itself, so keyword retrieval needs no external model and only the embedding and reranking stages consume API credentials — a cost and latency distinction that matters when budgeting a RAG stack. Developers and data engineers building production search or knowledge-base systems in Python can follow the Docker Compose deployment, PyMilvus setup and credential configuration step by step. Teams weighing Milvus against managed vector databases will find the self-hosted path, including Attu administration and port security, spelled out end to end.
A hands-on tutorial walks through building hybrid retrieval in Milvus, combining BM25 keyword search, dense vector semantic search, and Cross-Encoder reranking in a single workflow. The pipeline runs from service deployment to query: start Milvus, create a Collection, ingest text, run hybrid recall, then rerank the candidates. The tutorial covers deployment on a server via Docker Compose, with Milvus, etcd, MinIO and the Attu management UI running as containers, exposed on port 3000 for Attu and 19530 for application connections.
It explains the core functional split: the TEXTEMBEDDING function calls an embedding model (with DashScope credentials configured server-side) to generate dense vectors, BM25 produces sparse vectors inside Milvus without any external model, and RERANK reorders results based on the question and candidate text using a Cross-Encoder. PyMilvus is installed as the Python client with pip or uv, and connection details distinguish same-Docker-network addresses (milvus:19530) from external server IPs.
The design principle is that keyword retrieval captures proprietary terms while semantic retrieval finds paraphrases, so hybrid retrieval widens recall first and the Cross-Encoder then refines precision. For teams building RAG systems, this offers a deployable reference for the full knowledge-base ingestion and query loop, including operational notes such as first-run admin setup in Attu and restricting open ports to trusted IPs.
Python 实战检索优化:BM25、向量与重排
官网: Milvus 混合检索与 Cross-Encoder 精排 关键词检索 抓专有词, 语义检索 找相近意思;混合检索先扩大召回,再由 Cross-Encoder 精排 。下面从部署到调用,串起知识入库与检索流程。 流程: 启动服务 → 建立 Collection → 写入文本 → 混合召回 → 精排 核心区别: TEXTEMBEDDING 调用嵌入模型生成 dense 向量; BM25 在 Milvus 中生成 sparse 向量,不调用外部模型; RERANK 再根据问题和候选正文排序。 🚀 一、在宝塔服务器启动 Milvus 先安装 Docker 和 Docker Compose,并将 Milvus 部署配置放入服务器。截图红框标出了部署目录: 在宝塔终端或 SSH 中确认 Docker 可用,再进入部署目录启动: docker --version docker compose version cd /root/deploy docker compose up -d 检查容器状态: docker compose ps Milvus、etcd、MinIO 应为 Up 或 healthy ,Attu 应为 Up : 首次打开 Attu 管理页 http://服务器地址:3000 ,先创建管理员账户: 密码设为 8–128 位,并包含大写、小写、数字、符号中的至少三类。保存好账号;创建首位管理员后,公开注册关闭。 状态异常时查看日志: docker compose logs --tail = 100 端口: 3000 用于 Attu, 19530 用于应用连接。仅向可信 IP 开放。 📦 二、安装 PyMilvus PyMilvus 是 Python 客户端 ,安装在应用环境中使用;它不会启动 Milvus 服务: python3 -m pip install pymilvus 使用 uv 时: uv add pymilvus 验证安装: python3 -c "from pymilvus import MilvusClient; print ('PyMilvus 已安装')" 客户端版本需兼容服务端。连接失败时检查地址、端口和认证。 🧱 三、准备连接信息 Collection 是数据集合,Schema 定义字段和类型;Entity 是一条记录。 Attu 概览可查看版本、部署模式和连接地址: 地址填写: milvus:19530 仅适用于同一 Docker 网络。其他机器使用可访问的服务器 IP 或域名,并确保 19530 已开放;代码中的 uri 填这个地址。 🔐 四、配置模型凭证 在宝塔文件管理器中进入 /root/deploy/milvus/ ,把凭证合并到 Milvus 服务端配置。嵌入模型与 Cross-Encoder 共用此别名; BM25 不需要外部模型 。不要提交或公开真实 API Key: credential: dashscope_apikey: apikey: YOUR_DASHSCOPE_API_KEY function: textEmbedding: providers: dashscope: credential: dashscope_apikey rerank: model: providers: ali: credential: dashscope_apikey 保留原有配置,保存后重启服务: cd /root/deploy docker compose restart 🧩 五、封装向量库与调用 下面按执行顺序把建集合、写入、创建 ranker 和混合检索拆成小函数。先替换连接地址,并确认 向量维度与嵌入模型输出一致 。 from uuid import uuid4 from pymilvus import ( AnnSearchRequest, DataType, Function, FunctionType, MilvusClient, ) # 地址需要能从运行 Python 的机器访问。 client = MilvusClient(uri= "http://你的服务器地址:19530" ) collection_name = "knowledge_base" vector_dim = 1024 def create_collection (): # 已有集合就直接加载,避免重复创建。 if client.has_collection(collection_name): client.load_collection(collection_name) return schema = client.create_schema(auto_id= False , enable_dynamic_field= False ) # 主键、语义向量、BM25 向量,以及检索要返回的正文和标题。 schema.add_field( "id" , DataType.INT64, is_primary= True ) # 每条记录的唯一主键 schema.add_field( "dense" , DataType.FLOAT_VECTOR, dim=vector_dim) # 语义向量 schema.add_field( "sparse" , DataType.SPARSE_FLOAT_VECTOR) # BM25 关键词向量 schema.add_field( "h2" , DataType.VARCHAR, max_length= 128 ) # 标题,可用于展示/过滤 # VARCHAR 长度按字节计算;中文正文启用中文分词。 schema.add_field( "content" , DataType.VARCHAR, max_length= 65535 , enable_analyzer= True , analyzer_params={ "type" : "chinese" }, ) # 写入正文时由 Milvus 生成 BM25 稀疏向量。 schema.add_function(Function( name= "text_bm25_emb" , input_field_names=[ "content" ], output_field_names=[ "sparse" ], function_type=FunctionType.BM25, )) # TEXTEMBEDDING 由 Milvus 调用 DashScope,将正文转换为 dense 向量。 schema.add_function(Function( name= "text_embedding" , input_field_names=[ "content" ], output_field_names=[ "dense" ], function_type=FunctionType.TEXTEMBEDDING, params={ "provider" : "dashscope" , "model_name" : "text-embedding-v3" , "dim" : str (vector_dim), }, )) # 稠密向量用 COSINE;BM25 稀疏向量用倒排索引。 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_name=collection_name, schema=schema, index_params=indexes, ) client.load_collection(collection_name) def insert_documents ( documents: list [ dict ] ): # 每条输入至少包含 content,h2 可以省略。 if not documents: return [] # 调用前先建集合;每条记录使用唯一 INT64 主键。 create_collection() # Milvus INT64 主键为有符号整数,因此只取 UUID 的低 63 位。 ids = [uuid4(). int & (( 1 << 63 ) - 1 ) for _ in documents] # 只写入原文和标量字段,两个向量由 Schema 中的函数自动生成。 entities = [ { "id" : doc_id, "h2" : document.get( "h2" , "" ), "content" : document[ "content" ], } for doc_id, document in zip (ids, documents) ] client.insert(collection_name=collection_name, data=entities) return ids def create_cross_encoder_ranker ( query: str ): # Cross-Encoder 同时读取问题和候选正文,重新计算相关度。 return Function( name= "cross_encoder_ranker" , input_field_names=[ "content" ], function_type=FunctionType.RERANK, params={ "reranker" : "model" , # provider 与凭证别名需和服务端配置对应。 "provider" : "ali" , "model_name" : "qwen3.7-text-rerank" , "queries" : [query], # 每批最多交给模型处理 5 个候选。 "max_client_batch_size" : 5 , "credential" : "dashscope_apikey" , }, ) def hybrid_search ( query: str , fetch_k: int = 8 , top_k: int = 3 ): # 空问题或尚未创建集合时,不发起检索。 query = query.strip() if not query or not client.has_collection(collection_name): return [] client.load_collection(collection_name) # 每路先召回 fetch_k 个候选;dense 查询会调用嵌入模型,BM25 查询由 Milvus 处理。 dense_request = AnnSearchRequest( data=[query], anns_field= "dense" , param={}, limit=fetch_k ) sparse_request = AnnSearchRequest( data=[query], anns_field= "sparse" , param={}, limit=fetch_k ) # ranker 负责融合后的精排;top_k 是最终返回数量。 results = client.hybrid_search( collection_name=collection_name, reqs=[dense_request, sparse_request], ranker=create_cross_encoder_ranker(query), limit=top_k, output_fields=[ "content" , "h2" ], ) # data 只有一个查询,因此取第一组命中结果。 return results[ 0 ] if results else [] # 写入时准备集合并存入原文;Milvus 自动生成 dense 和 sparse 向量。 insert_documents([ { "h2" : "连接排查" , "content" : "蓝牙设备反复断连时,可以先检查电量,再删除配对记录并重新连接。" }, { "h2" : "充电问题" , "content" : "耳机无法充电时,先清理充电触点,并确认充电盒电量充足。" }, ]) hits = hybrid_search( "无线耳机总是断开连接,先检查哪些地方?" ) for hit in hits: # entity 是命中的字段;distance 是 Milvus 返回的相关度分数。 entity = hit[ "entity" ] print ( f" {hit[ 'distance' ]: .4 f} | {entity[ 'h2' ]} | {entity[ 'content' ]} " ) 代码顺序: create_collection() 建集合 → insert_documents() 写入正文 → hybrid_search() 检索。Milvus 的 TEXTEMBEDDING 在入库和查询时生成稠密向量; BM25 不调用外部模型 。两路各召回 fetch_k 条,再由 RERANK 精排并返回 top_k 条。 ⭐ 六、排查重点 结果不理想时,先确认相关内容能否进入候选;候选正确但排序靠后,再检查凭证、重排模型和候选数。增大 fetch_k 可扩展重排范围,也会增加耗时; top_k 控制最终返回条数。 🌱 结束语 至此,Milvus 已能接收文本、自动生成向量,并在检索时结合关键词与语义召回,再用 Cross-Encoder 排序。接入自己的知识时,准备相同的 content 、 h2 字段,并确认向量维度、模型凭证和服务器地址一致。 📚 参考网站 Milvus 官方文档 PyMilvus 3.0:混合检索 API PyMilvus 3.0:Function 与模型重排 PyMilvus 3.0:FunctionType Milvus:BM25 函数 百炼:text-embedding-v3 模型 百炼:qwen3.7-text-rerank 模型
This report is categorized under AITOP's "How-to" desk, focusing on China's AI industry and domestic foundation model ecosystem. Within our cross-regional analytical framework, it directly maps to AI developer toolchains, coding agents, and engineering workflows. Key entities and technical topics under continuous tracking include Milvus, PyMilvus, BM25, DashScope.
Source attribution: curated from 掘金本周最热 (@Dragon_xjy).