Milvus
→ 返回 向量数据库
Milvus 是开源的分布式向量数据库,专为海量向量的高性能相似度搜索设计,是 RAG、推荐系统、图像搜索等 AI 应用的主流选择。
核心概念
概念 类比关系型数据库 说明 Collection 表 存储向量和元数据的基本单元 Field 列 支持向量字段和标量字段 Entity 行 一条数据记录 Index 索引 加速向量搜索的数据结构 Partition 分区 Collection 的逻辑划分
部署方式
模式 适用场景 Milvus Lite 本地开发,pip 安装即用 Standalone 单机生产,依赖 etcd + MinIO Cluster 分布式生产,各组件独立扩缩容
# Milvus Lite(开发)
pip install pymilvus
# Standalone(Docker Compose)
docker compose up -d
向量索引类型
索引 说明 适用场景 FLAT 暴力搜索,精确 数据量 < 100w,要求精确召回 IVF_FLAT 倒排分桶加速 中等规模,平衡精度与速度 IVF_SQ8 IVF + 标量量化压缩 内存敏感场景 HNSW 层级图结构,搜索极快 高 QPS 低延迟,最常用 DISKANN 磁盘索引 超大规模(数十亿向量)
距离度量
度量 说明 适用场景 L2(欧氏距离) 值越小越相似 图像、音频特征向量 IP(内积) 值越大越相似 已归一化的文本 Embedding COSINE(余弦相似度) 值越大越相似 文本语义搜索(推荐)
Python SDK 示例
创建 Collection
from pymilvus import MilvusClient, DataType
client = MilvusClient( uri = "http://localhost:19530" )
schema = MilvusClient.create_schema( auto_id = True , enable_dynamic_field = True )
schema.add_field( "id" , DataType. INT64 , is_primary = True )
schema.add_field( "embedding" , DataType. FLOAT_VECTOR , dim = 1536 )
schema.add_field( "content" , DataType. VARCHAR , max_length = 2000 )
schema.add_field( "source" , DataType. VARCHAR , max_length = 200 )
index_params = client.prepare_index_params()
index_params.add_index(
field_name = "embedding" ,
index_type = "HNSW" ,
metric_type = "COSINE" ,
params = { "M" : 16 , "efConstruction" : 200 }
)
client.create_collection(
collection_name = "documents" ,
schema = schema,
index_params = index_params
)
写入向量
data = [
{ "embedding" : get_embedding(chunk), "content" : chunk, "source" : "doc_001" }
for chunk in text_chunks
]
client.insert( collection_name = "documents" , data = data)
相似度搜索
query_vec = get_embedding( "什么是向量数据库?" )
results = client.search(
collection_name = "documents" ,
data = [query_vec],
limit = 5 ,
output_fields = [ "content" , "source" ],
search_params = { "ef" : 100 }
)
for hit in results[ 0 ]:
print ( f "距离: { hit[ 'distance' ] :.4f } 内容: { hit[ 'entity' ][ 'content' ] } " )
混合搜索(向量 + 标量过滤)
results = client.search(
collection_name = "documents" ,
data = [query_vec],
filter = "source == 'doc_001'" ,
limit = 5 ,
output_fields = [ "content" , "source" ]
)
RAG 集成模式
用户问题
→ 生成 Query Embedding
→ Milvus 向量搜索 Top-K 文档块
→ 组装 Prompt(问题 + 文档块)
→ LLM 生成回答
Spring Boot 集成(Spring AI)
< dependency >
< groupId >org.springframework.ai</ groupId >
< artifactId >spring-ai-milvus-store-spring-boot-starter</ artifactId >
</ dependency >
spring :
ai :
vectorstore :
milvus :
client :
host : localhost
port : 19530
collection-name : documents
embedding-dimension : 1536
index-type : HNSW
metric-type : COSINE
@ Service
@ RequiredArgsConstructor
public class RagService {
private final VectorStore vectorStore;
public void ingest (List< Document > docs ) {
vectorStore. add (docs);
}
public List< Document > search (String question ) {
return vectorStore. similaritySearch (
SearchRequest. query (question). withTopK ( 5 )
);
}
}
相关