【Milvus】向量数据库pymilvus使用教程

以下是根据 Milvus 官方文档整理的详细 PyMilvus 使用教程,基于 Milvus 2.5.x 版本:


PyMilvus 使用教程

目录

  1. 安装与环境准备
  2. 连接 Milvus 服务
  3. 数据模型基础概念
  4. 创建集合(Collection)
  5. 插入数据
  6. 创建索引
  7. 向量搜索
  8. 删除操作
  9. 完整示例
  10. 注意事项

安装与环境准备

搭建 Milvus 服务 基于Docker

# 记得提前安装Docker
curl -sfL https://raw.githubusercontent.com/milvus-io/milvus/master/scripts/standalone_embed.sh -o standalone_embed.sh

bash standalone_embed.sh start

# 数据可视化工具
docker run -p 8000:3000 -e MILVUS_URL=你的IP:19530 zilliz/attu:v2.5
pip install pymilvus

要求

  • Python 3.10+
  • Milvus 2.5.x 服务(单机版或集群)

连接 Milvus 服务

from pymilvus import connections

# 连接单机版
connections.connect(
    alias="default",
    host="localhost",
    port="19530"
)

# 连接集群或云服务(如Zilliz Cloud)
# connections.connect(
#     alias="cloud",
#     uri="https://xxx.api.region.zillizcloud.com",
#     token="your_api_key"
# )

数据模型基础概念

  • Collection: 类似数据库的表,包含多个字段
  • Schema: 定义字段类型和约束
  • Partition: 数据分区,用于优化查询性能
  • Index: 加速向量搜索的索引结构

创建集合(Collection)

from pymilvus import (
    FieldSchema, CollectionSchema, DataType,
    Collection
)

# 定义字段
fields = [
    FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=True),
    FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=128),
    FieldSchema(name="age", dtype=DataType.INT32)
]

# 创建Schema
schema = CollectionSchema(fields, description="人脸特征向量库")

# 创建Collection
collection = Collection(name="face_db", schema=schema)

参数说明

  • auto_id: 是否自动生成主键
  • dim: 向量维度(必须与后续插入数据维度一致)

插入数据

import random

# 生成随机数据
num_entities = 1000
vectors = [[random.random() for _ in range(128)] for _ in range(num_entities)]
ages = [random.randint(18, 65) for _ in range(num_entities)]

# 构造插入数据
data = [
    vectors,  # 对应embedding字段
    ages       # 对应age字段
]

# 插入数据
insert_result = collection.insert(data)

# 获取自动生成的ID
print(insert_result.primary_keys)

创建索引

index_params = {
    "index_type": "IVF_FLAT",
    "metric_type": "L2",
    "params": {"nlist": 128}
}

collection.create_index(
    field_name="embedding",
    index_params=index_params
)

常用索引类型

  • FLAT: 精确搜索
  • IVF_FLAT: 平衡型
  • HNSW: 高召回率
  • DISKANN: 磁盘存储优化

向量搜索

# 加载集合到内存
collection.load()

# 准备搜索向量
search_vector = [random.random() for _ in range(128)]

# 构建搜索参数
search_params = {
    "metric_type": "L2",
    "params": {"nprobe": 10}
}

# 执行搜索
results = collection.search(
    data=[search_vector],
    anns_field="embedding",
    param=search_params,
    limit=5,
    output_fields=["age"]  # 返回的额外字段
)

# 解析结果
for hits in results:
    for hit in hits:
        print(f"ID: {hit.id}, 距离: {hit.distance}, Age: {hit.entity.get('age')}")

删除操作

# 删除实体
expr = "age >= 60"
collection.delete(expr)

# 删除集合
collection.drop()

完整示例

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

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

# 创建集合
fields = [
    FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=True),
    FieldSchema(name="vector", dtype=DataType.FLOAT_VECTOR, dim=128)
]
schema = CollectionSchema(fields)
collection = Collection("test_collection", schema)

# 插入数据
data = [[[random.random() for _ in range(128)] for _ in range(1000)]]
collection.insert(data)

# 创建索引
index_params = {"index_type": "IVF_FLAT", "metric_type": "L2", "params": {"nlist": 100}}
collection.create_index("vector", index_params)
collection.load()

# 搜索
search_params = {"metric_type": "L2", "params": {"nprobe": 10}}
results = collection.search(
    data=[[0.5]*128],
    anns_field="vector",
    param=search_params,
    limit=3
)

# 输出结果
print("搜索结果:")
for hits in results:
    for hit in hits:
        print(f"ID: {hit.id}, 距离: {hit.distance}")

# 清理
collection.drop()

注意事项

  1. 版本兼容性:确保 PyMilvus 版本与 Milvus 服务端版本匹配
  2. 资源管理
    • 搜索前必须调用 load() 加载集合
    • 大数据量时注意内存使用
  3. 索引选择:根据数据规模和性能需求选择合适索引类型
  4. 数据预处理:确保向量维度与 schema 定义一致
  5. 分页查询:大数据量查询使用 offset + limit 分页

官方文档参考:

建议结合具体业务需求调整参数,并针对实际数据量进行性能测试。

Milvus是一款开源的分布式向量数据库,专用于处理大规模的高维向量数据。Attu是它的一个重要组件,通常被称为"Attentive Query Understanding",即注意力查询理解模块,主要用于提升搜索的精度和性能。 以下是使用Milvus Attu的基本步骤: 1. **安装与初始化**: 首先需要从GitHub上下载 Milvus 源码并按照官方文档设置环境。安装完成后,创建一个新的库并配置索引。 ```bash pip install Milvus milvus-client create_collection -collection_name my_collection -fields ... (列举字段) ``` 2. **向数据库插入数据**: 使用`insert_vectors`函数将向量数据分批插入到库中。 ```python import milvus milvus_client = milvus.Milvus('localhost', '19530') vector = [...] # 向量数据 milvus_client.insert([{"collection_name": "my_collection", "data": vector}]) ``` 3. **启用Attu**: Attu功能通常作为插件或API集成的一部分,在创建搜索任务时启用。例如,在Python SDK中,可以指定使用Attu模型执行搜索。 ```python search_param = { "query_records": [...], # 查询向量 "top_k": 10, "metric_type": "IP", "params": {"model_type": "attu"} # 如果有Attu,则设置此参数 } res = milvus_client.search("my_collection", search_param) ``` 4. **查询与分析**: 使用`search`或`predict`函数执行基于向量的查询,Attu会提供更智能的搜索结果排序和预测。 注意:实际操作时,需根据最新的Milvus版本文档和Attu的官方文档来调整细节。同时,Attu作为高级特性,可能需要特定的训练模型才能正常使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值