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_SQ8IVF + 标量量化压缩内存敏感场景
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)
        );
    }
}

相关

  • Pinecone — 全托管云端向量数据库,无需自建
  • Qdrant — 开源向量数据库,Rust 编写,性能优秀
  • PostgreSQL — pgvector 扩展,小规模向量搜索
  • Elasticsearch — dense_vector 类型,兼顾全文搜索与向量搜索
  • 大模型 — Embedding 模型生成向量,LLM 生成回答