Milvus:云原生分布式向量数据库

FreeGuideOnline 最新 2026-07-02

bash wget https://github.com/milvus-io/milvus/releases/download/v2.4.0/milvus-standalone-docker-compose.yml -O docker-compose.yml docker compose up -d

随后可通过 **Attu**(官方可视化工具)或 Python SDK 连接。

### Python SDK 安装
```bash
pip install pymilvus

创建集合与插入数据

from pymilvus import connections, Collection, FieldSchema, CollectionSchema, DataType

# 连接
connections.connect(host='localhost', port='19530')

# 定义字段
pk_field = FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=False)
vec_field = FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=128)
text_field = FieldSchema(name="text", dtype=DataType.VARCHAR, max_length=200)

# 创建 Schema 与集合
schema = CollectionSchema(fields=[pk_field, vec_field, text_field], description="demo")
collection = Collection(name="demo_collection", schema=schema)

# 插入数据(示例随机向量)
import random
entities = [
    [i for i in range(1000)],                         # id
    [[random.random() for _ in range(128)] for _ in range(1000)],  # embedding
    [f"text_{i}" for i in range(1000)]               # text
]
collection.insert(entities)
collection.flush()

建立索引

index_params = {
    "metric_type": "IP",            # 内积相似度
    "index_type": "IVF_FLAT",
    "params": {"nlist": 128}
}
collection.create_index(field_name="embedding", index_params=index_params)

执行搜索

collection.load()   # 将数据加载至内存(或由查询节点管理)

# 生成随机查询向量
query_vec = [[random.random() for _ in range(128)]]

search_params = {"metric_type": "IP", "params": {"nprobe": 16}}
results = collection.search(
    data=query_vec,
    anns_field="embedding",
    param=search_params,
    limit=5,
    output_fields=["text"]
)

for hits in results:
    for hit in hits:
        print(f"id: {hit.id}, distance: {hit.distance}, text: {hit.entity.get('text')}")

混合搜索示例:标量过滤

results = collection.search(
    data=query_vec,
    anns_field="embedding",
    param=search_params,
    limit=5,
    expr='text like "text_1%"',   # 标量过滤条件
    output_fields=["text"]
)

进阶配置

索引参数调优

  • IVF_FLATnlist 决定聚类中心数量,典型取值 1024~65536。nprobe 为搜索时查询的聚类数,增大可提升召回率但降低速度。
  • HNSWM 为每层最大出边数(通常4~64),efConstruction 影响索引构建质量,ef 为搜索时动态候选集大小。高 ef 值可提升召回率。
  • DISKANN:适合十亿级以上向量,索引存于高性能 SSD。需配置 search_list 等参数控制磁盘 IO 与召回率。

动态 Schema 与 Partition 管理

启用动态 Schema 可让集合自动存储未预先定义的字段,灵活应对多变数据。通过 partition_name 参数在插入时指定分区,查询时可限定分区范围,避免全量扫描。

一致性级别

Milvus 支持四种一致性保证:StrongBoundedEventuallySession。在分布式写入场景下,根据业务需要选择合适的一致性来平衡实时性与性能。

与 LLM 应用集成

Milvus 是构建检索增强生成(RAG)的首选向量库。典型工作流:

  1. 将文档切割为块(chunk),用嵌入模型(如 text-embedding-3-small)生成向量。
  2. 向量与原文存入 Milvus。
  3. 用户提问时,同样生成查询向量,在 Milvus 中进行语义检索。
  4. 将检索到的上下文片段与问题一并提交给大模型,生成带知识背景的回答。

与 LangChain、LlamaIndex 等框架深度集成,一行代码即可切换底层向量存储为 Milvus:

from langchain.vectorstores import Milvus
vector_store = Milvus(embedding_function=embeddings, collection_name="rag_docs")