Milvus 向量数据库快速入门

一、什么是 Milvus?

Milvus 是一款开源的向量数据库,用于存储、管理和检索高维向量数据。它适合构建各种 AI 场景下的向量检索系统,如推荐、图像搜索、问答系统等。

概念关系图(逻辑结构)

json 复制代码
Milvus数据库
├── Collection集合
│   ├── Partition分区
│   │   └── Entity实体
│   │       └── Fields字段(向量 + 元数据)
│   ├── Schema结构
│   └── Index索引
├── 查询操作(Search / Query)
└── 数据一致性机制

二、Milvus 核心概念速查表

实体 Entity 示例

json 复制代码
{
  "id": 1,
  "embedding": [0.1, 0.2, 0.3, ...],
  "title": "iPhone",
  "price": 999.0
}

三、核心操作流程

四、一致性模型与数据安全保障

Milvus 提供以下一致性保证:

五、索引类型选择指南

六、进阶知识点补充

七、实战:使用 Python SDK 完整示例(基于 Milvus 2.x)

环境准备

python 复制代码
pip install pymilvus

初始化连接

python 复制代码
from pymilvus import connections
connections.connect(alias="default", host="localhost", port="19530")

创建 Collection

python 复制代码
from pymilvus import FieldSchema, CollectionSchema, DataType, Collection
fields = [
    FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=True),
    FieldSchema(name="title", dtype=DataType.VARCHAR, max_length=200),
    FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=128)
]
schema = CollectionSchema(fields, description="商品向量集合")
collection = Collection(name="product_vectors", schema=schema)

插入数据

python 复制代码
import numpy as np
titles = ["iPhone", "MacBook", "AirPods"]
vectors = [np.random.rand(128).tolist() for _ in range(3)]
collection.insert([titles, vectors])
collection.flush()

创建索引 & 加载数据

python 复制代码
index_params = {
    "index_type": "IVF_FLAT",
    "metric_type": "L2",
    "params": {"nlist": 128}
}
collection.create_index(field_name="embedding", index_params=index_params)
collection.load()

向量搜索 + 条件过滤(Hybrid Search)

python 复制代码
query_vector = [np.random.rand(128).tolist()]
search_params = {"metric_type": "L2", "params": {"nprobe": 10}}
results = collection.search(
    data=query_vector,
    anns_field="embedding",
    param=search_params,
    limit=5,
    expr="title like 'Mac%'"
)
for hits in results:
    for hit in hits:
        print(f"id: {hit.id}, distance: {hit.distance}")

八、常见踩坑提醒

九、真实应用场景参考:电商推荐系统

十、快速上手建议

✅ 推荐

  • 从创建 Collection 开始,理解字段与向量的对应关系
  • 一步步插入数据、构建索引、执行搜索
  • 多关注向量维度、索引类型和内存管理

❌ 避免

  • 向量维度不统一
  • 未加载数据就开始搜索
相关推荐
qq_372906934 分钟前
Python最短路径怎么求_Dijkstra算法与优先队列结合
jvm·数据库·python
qq_330037994 分钟前
如何查看集群版本_crsctl query crs activeversion当前版本
jvm·数据库·python
DROm RAPS9 分钟前
SQL 实战:复杂数据去重与唯一值提取
前端·数据库·sql
m0_7375393711 分钟前
MYSQL源码安装和备份
数据库·mysql·adb
214396519 分钟前
golang如何使用expvar暴露运行时指标_golang expvar运行时指标暴露步骤
jvm·数据库·python
翻斗包菜26 分钟前
【MongoDB 从入门到实战:安装、配置、CRUD、权限、备份恢复全教程】
数据库·mongodb
weixin_4249993632 分钟前
如何用SQL按条件计算移动求和_结合CASE与窗口函数
jvm·数据库·python
214396533 分钟前
持久化存储如何适配不同浏览器?解决隐私模式下存储失败的指南
jvm·数据库·python
justjinji34 分钟前
c++怎么读取大端序设备的固件bin文件_字节反转与位移操作【详解】
jvm·数据库·python
m0_5150984238 分钟前
如何处理视图中的Definer_视图创建者权限变更对视图有效性的影响
jvm·数据库·python