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

打印 上一主题 下一主题

主题 861|帖子 861|积分 2583

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

PyMilvus 利用教程

目次


  • 安装与情况准备
  • 毗连 Milvus 服务
  • 数据模型基础概念
  • 创建集合(Collection)
  • 插入数据
  • 创建索引
  • 向量搜索
  • 删除操作
  • 完备示例
  • 注意事项

安装与情况准备

搭建 Milvus 服务 基于Docker

  1. # 记得提前安装Docker
  2. curl -sfL https://raw.githubusercontent.com/milvus-io/milvus/master/scripts/standalone_embed.sh -o standalone_embed.sh
  3. bash standalone_embed.sh start
  4. # 数据可视化工具
  5. docker run -p 8000:3000 -e MILVUS_URL=你的IP:19530 zilliz/attu:v2.5
复制代码
  1. pip install pymilvus
复制代码
要求


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

毗连 Milvus 服务

  1. from pymilvus import connections
  2. # 连接单机版
  3. connections.connect(
  4.     alias="default",
  5.     host="localhost",
  6.     port="19530"
  7. )
  8. # 连接集群或云服务(如Zilliz Cloud)
  9. # connections.connect(
  10. #     alias="cloud",
  11. #     uri="https://xxx.api.region.zillizcloud.com",
  12. #     token="your_api_key"
  13. # )
复制代码

数据模型基础概念



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

创建集合(Collection)

  1. from pymilvus import (
  2.     FieldSchema, CollectionSchema, DataType,
  3.     Collection
  4. )
  5. # 定义字段
  6. fields = [
  7.     FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=True),
  8.     FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=128),
  9.     FieldSchema(name="age", dtype=DataType.INT32)
  10. ]
  11. # 创建Schema
  12. schema = CollectionSchema(fields, description="人脸特征向量库")
  13. # 创建Collection
  14. collection = Collection(name="face_db", schema=schema)
复制代码
参数说明


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

插入数据

  1. import random
  2. # 生成随机数据
  3. num_entities = 1000
  4. vectors = [[random.random() for _ in range(128)] for _ in range(num_entities)]
  5. ages = [random.randint(18, 65) for _ in range(num_entities)]
  6. # 构造插入数据
  7. data = [
  8.     vectors,  # 对应embedding字段
  9.     ages       # 对应age字段
  10. ]
  11. # 插入数据
  12. insert_result = collection.insert(data)
  13. # 获取自动生成的ID
  14. print(insert_result.primary_keys)
复制代码

创建索引

  1. index_params = {
  2.     "index_type": "IVF_FLAT",
  3.     "metric_type": "L2",
  4.     "params": {"nlist": 128}
  5. }
  6. collection.create_index(
  7.     field_name="embedding",
  8.     index_params=index_params
  9. )
复制代码
常用索引类型


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

向量搜索

  1. # 加载集合到内存
  2. collection.load()
  3. # 准备搜索向量
  4. search_vector = [random.random() for _ in range(128)]
  5. # 构建搜索参数
  6. search_params = {
  7.     "metric_type": "L2",
  8.     "params": {"nprobe": 10}
  9. }
  10. # 执行搜索
  11. results = collection.search(
  12.     data=[search_vector],
  13.     anns_field="embedding",
  14.     param=search_params,
  15.     limit=5,
  16.     output_fields=["age"]  # 返回的额外字段
  17. )
  18. # 解析结果
  19. for hits in results:
  20.     for hit in hits:
  21.         print(f"ID: {hit.id}, 距离: {hit.distance}, Age: {hit.entity.get('age')}")
复制代码

删除操作

  1. # 删除实体
  2. expr = "age >= 60"
  3. collection.delete(expr)
  4. # 删除集合
  5. collection.drop()
复制代码

完备示例

  1. from pymilvus import connections, FieldSchema, CollectionSchema, DataType, Collection
  2. # 连接服务
  3. connections.connect(host='localhost', port='19530')
  4. # 创建集合
  5. fields = [
  6.     FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=True),
  7.     FieldSchema(name="vector", dtype=DataType.FLOAT_VECTOR, dim=128)
  8. ]
  9. schema = CollectionSchema(fields)
  10. collection = Collection("test_collection", schema)
  11. # 插入数据
  12. data = [[[random.random() for _ in range(128)] for _ in range(1000)]]
  13. collection.insert(data)
  14. # 创建索引
  15. index_params = {"index_type": "IVF_FLAT", "metric_type": "L2", "params": {"nlist": 100}}
  16. collection.create_index("vector", index_params)
  17. collection.load()
  18. # 搜索
  19. search_params = {"metric_type": "L2", "params": {"nprobe": 10}}
  20. results = collection.search(
  21.     data=[[0.5]*128],
  22.     anns_field="vector",
  23.     param=search_params,
  24.     limit=3
  25. )
  26. # 输出结果
  27. print("搜索结果:")
  28. for hits in results:
  29.     for hit in hits:
  30.         print(f"ID: {hit.id}, 距离: {hit.distance}")
  31. # 清理
  32. collection.drop()
复制代码

注意事项


  • 版本兼容性:确保 PyMilvus 版本与 Milvus 服务端版本匹配
  • 资源管理

    • 搜索前必须调用 load() 加载集合
    • 大数据量时注意内存利用

  • 索引选择:根据数据规模和性能需求选择符合索引类型
  • 数据预处置惩罚:确保向量维度与 schema 界说一致
  • 分页查询:大数据量查询利用 offset + limit 分页
官方文档参考:


  • Milvus Documentation
  • PyMilvus API Reference
建议结合具体业务需求调解参数,并针对实际数据量进行性能测试。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

瑞星

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表