高性能向量数据库——Milvus

1、什么是RAG?为什么所有大模型应用都离不开它?

什么是RAG?

RAG 是一种结合 “外部知识库检索” 与 “生成式模型” 的架构。流程如下:

  • 检索阶段:将用户输入转换成向量,到知识库中检索相关资料(如文档段落、FAQ、笔记等)
  • 生成阶段:将检索到的资料作为上下文,交给大模型进行生成

简单说,就是给大模型“喂资料”,让它基于“事实”回答问题。

大模型不能“凭空造物”

当你对ChatGPT、Claude、Gemini等大模型提问时,它们的回答似乎“无所不知”,但实际上,很多大模型并不具备实时的、外部世界知识。它们依赖于“预训练数据”的记忆,而这种“记忆”一旦训练完毕就难以更新。

你问它“2025年7月上海哪个区房价最高?”它可能无法正确回答,因为它的知识截止于2024年。

怎么办?这时我们就需要 Retrieval-Augmented Generation(检索增强生成)

举个例子

假设你在开发一个企业内部的智能客服机器人,面对的问题如:

“请问员工入职后多久可以申请年假?”

传统大模型可能“编”出一个标准答案。但如果你用RAG接入公司的人事手册,让模型先去“查”,再基于文档内容回答,就能生成更加符合真实业务的答案。

2、RAG靠什么“查”?这就是向量数据库的舞台

为什么不能用传统数据库?

传统关系型数据库(如MySQL)依赖结构化字段和关键词查询(SQL),但语义搜索的需求更复杂。例如:

  • 用户问:“员工可以什么时候请假?”
  • 文档中写的是:“入职满三个月的员工可申请年假。”

关键词完全不匹配,但语义是相关的。怎么办?

这就需要一种能理解“语义相似度”的数据库 —— 向量数据库。

向量数据库的核心能力

向量数据库的核心功能是:

  • 向量存储:将文本、图像、音频等非结构化数据转为高维向量存储
  • 相似度搜索:基于欧几里得距离、余弦相似度等,快速找出“最像”的数据
  • 高性能检索:支持上亿条向量毫秒级搜索,且具备分布式能力

向量数据库是为“模糊匹配”和“语义相关”量身打造的。

举个例子

我们将下面两个句子转成向量:

  • 用户问题:“怎么申请请假?”
  • 知识库内容:“员工可通过OA系统提交请假申请”

虽然一个说“请假”,一个说“提交申请”,但它们转成向量后,余弦相似度接近,就能成功匹配。传统关键词搜索完全做不到。

3、Milvus简介

Milvus 是一个开源的高性能向量数据库,专门用于管理、存储和搜索海量的向量数据。它广泛应用于 AI、机器学习、推荐系统、图像和视频检索等领域,支持快速的相似度搜索和向量索引构建。

Milvus 支持多种索引类型和检索算法,能够处理数十亿条向量,实现毫秒级的检索响应。它的底层架构基于分布式设计,支持水平扩展,适合大规模生产环境。

4、特点

  • 高性能检索:支持多种索引结构(如 IVF、HNSW、ANNOY 等),满足不同精度与速度需求,支持 GPU 加速。
  • 分布式架构:支持多节点集群部署,实现数据分片和负载均衡,保证高可用和扩展性。
  • 多模支持:支持多种向量数据类型(浮点型、二进制向量等),方便集成不同应用场景。
  • 丰富的API接口:提供 Python、Go、Java、RESTful 等多语言客户端,便于快速开发和集成。
  • 易用性强:支持SQL-like的查询表达式,用户体验友好,方便快速上手。
  • 云原生兼容:支持容器化部署(Docker、Kubernetes),便于在云环境中管理。

5、使用场景

  • 智能推荐系统:利用用户行为生成向量,进行相似度检索,为用户推荐相关内容或商品。
  • 图像与视频检索:对图片和视频特征向量进行存储与搜索,实现视觉内容的快速匹配。
  • 自然语言处理:存储文本向量(如句子、段落、文档),支持语义搜索和文本相似度计算。
  • 生物信息学: 处理基因序列和蛋白质结构向量,进行快速比对和分类。
  • 安全监控与异常检测:利用行为向量化数据,快速识别异常模式和安全威胁。

6、主流向量数据库对比

数据库开源支持索引是否分布式说明
MilvusIVF, HNSW, PQ社区最活跃,生产可用
FAISSIVF, HNSW, PQFacebook 开源,单机工具库
WeaviateHNSWRESTful 风格 API 强
PineconeHNSW/PQ✅(托管)商业化闭源服务
QdrantHNSW支持动态分片与 payload 过滤
VespaHNSW强大但复杂,雅虎主导开发

📌 结论:如果你需要自己部署、强性能、社区活跃、中文文档好 → 首选 Milvus

7、安装部署

wget https://github.com/milvus-io/milvus/releases/download/v2.6.0-rc1/milvus-standalone-docker-compose.yaml -O docker-compose.yml

root@huqi-virtual-machine:~/milvus# docker-compose up -d
Creating network "milvus" with the default driver
Creating milvus-minio ... done
Creating milvus-etcd  ... done
Creating milvus-standalone ... done
root@huqi-virtual-machine:~/milvus# docker ps
CONTAINER ID   IMAGE                                      COMMAND                   CREATED         STATUS                            PORTS                                                                                      NAMES
4a06f5cca22f   milvusdb/milvus:v2.6.0-rc1                 "/tini -- milvus run…"   5 seconds ago   Up 4 seconds (health: starting)   0.0.0.0:9091->9091/tcp, :::9091->9091/tcp, 0.0.0.0:19530->19530/tcp, :::19530->19530/tcp   milvus-standalone
51173d80675c   quay.io/coreos/etcd:v3.5.18                "etcd -advertise-cli…"   7 seconds ago   Up 5 seconds (health: starting)   2379-2380/tcp                                                                              milvus-etcd
0d03efcdc0c8   minio/minio:RELEASE.2023-03-20T20-16-18Z   "/usr/bin/docker-ent…"   7 seconds ago   Up 5 seconds (health: starting)   0.0.0.0:9000-9001->9000-9001/tcp, :::9000-9001->9000-9001/tcp                              milvus-minio

#安装依赖
sudo apt update
sudo apt install python3-pip -y
pip install pymilvus==2.6.0b0

8、用 Python 玩转 Milvus

项目结构

milvus/
├── docker-compose.yml        # Milvus 一键部署文件(未展示)
├── list_collections.py       # 查看当前所有集合
├── query_collection_data.py  # 查询集合中的数据(命令行参数)
└── test_milvus.py            # 创建集合、插入、搜索、更新、删除

完整功能测试(增、删、改、查)

root@huqi-virtual-machine:~/milvus# cat test_milvus.py 
# -*- coding: utf-8 -*-
from pymilvus import (
    connections, utility,
    FieldSchema, CollectionSchema, DataType,
    Collection
)
import numpy as np

# 1. 连接 Milvus
connections.connect("default", host="localhost", port="19530")

# 2. 定义 Schema(主键 + 标题 + 向量)
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=8),
]
schema = CollectionSchema(fields=fields, description="商品向量集合", enable_dynamic_field=True)

# 3. 创建集合
collection_name ="product_8d_collection"
if utility.has_collection(collection_name):
    utility.drop_collection(collection_name)

product_collection = Collection(name=collection_name, schema=schema, consistency_level="Strong")
print(f"✅ 集合创建成功: {collection_name}")

# 4. 插入多条数据
titles = ["iPhone 15", "iPhone 14", "iPhone 13 Pro", "Samsung S23", "Huawei Mate60"]
vectors = np.random.rand(5, 8).tolist()
entities = [titles, vectors]
insert_result = product_collection.insert(entities)
print(f"✅ 成功插入 {len(titles)} 条记录")

# 5. 创建索引
index_params = {
    "index_type": "IVF_FLAT",
    "metric_type": "L2",
    "params": {"nlist": 1024}
}
product_collection.create_index(field_name="embedding", index_params=index_params)
print("✅ 向量索引创建成功")

# 6. 加载集合
product_collection.load()
print("✅ 集合加载成功")

# 7. 查询 title 包含 "iPhone" 的数据
result = product_collection.query(
    expr="title like 'iPhone%'",
    output_fields=["id", "title"]
)
print("✅ 查询包含 iPhone 的记录:")
for item in result:
    print(f"  ID: {item['id']}, Title: {item['title']}")

# 8. 更新其中一条记录(更新 title)
existing_id = result[0]['id']
product_collection.upsert(
    data=[
        [existing_id],  # ID
        ["iPhone 15 Pro Max"],  # 新 title
        [np.random.rand(8).tolist()]  # 新向量
    ]
)
print(f"✅ 已更新 ID={existing_id} 的记录 title 为 iPhone 15 Pro Max")

# 9. 删除一条记录
delete_id = result[1]['id']
product_collection.delete(f"id in [{delete_id}]")
print(f"✅ 已删除 ID={delete_id} 的记录")

# 10. 向量搜索
query_vector = [np.random.rand(8).tolist()]
search_params = {"metric_type": "L2", "params": {"nprobe": 10}}

search_result = product_collection.search(
    data=query_vector,
    anns_field="embedding",
    param=search_params,
    limit=3,
    output_fields=["title"]
)

print("✅ 向量搜索结果:")
for hit in search_result[0]:
    print(f"  ID: {hit.id}, 距离: {hit.distance:.4f}, Title: {hit.entity.get('title')}")


#执行脚本
root@huqi-virtual-machine:~/milvus# python3 test_milvus.py 
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at schema.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at common.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at milvus.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at rg.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at feder.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at msg.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
✅ 集合创建成功: product_8d_collection
✅ 成功插入 5 条记录
✅ 向量索引创建成功
✅ 集合加载成功
✅ 查询包含 iPhone 的记录:
  ID: 459465252515875226, Title: iPhone 15
  ID: 459465252515875227, Title: iPhone 14
  ID: 459465252515875228, Title: iPhone 13 Pro
✅ 已更新 ID=459465252515875226 的记录 title 为 iPhone 15 Pro Max
✅ 已删除 ID=459465252515875227 的记录
✅ 向量搜索结果:
  ID: 459465252515875231, 距离: 0.8764, Title: iPhone 15 Pro Max
  ID: 459465252515875228, 距离: 1.1409, Title: iPhone 13 Pro
  ID: 459465252515875229, 距离: 1.1454, Title: Samsung S23
https://wxa.wxs.qq.com/tmpl/ml/base_tmpl.html

查看当前集合列表

root@huqi-virtual-machine:~/milvus# cat list_collections.py 
# -*- coding: utf-8 -*-
from pymilvus import connections, utility

# Connect to Milvus
connections.connect("default", host="localhost", port="19530")

# List all collections
collections = utility.list_collections()

print("Collections in Milvus:")
for name in collections:
    print(f" - {name}")
    
#执行脚本
root@huqi-virtual-machine:~/milvus# python3 list_collections.py 
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at schema.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at common.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at milvus.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at rg.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at feder.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at msg.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
Collections in Milvus:
- product_8d_collection

查询集合数据(支持命令行参数)

https://wxa.wxs.qq.com/tmpl/ml/base_tmpl.html
root@huqi-virtual-machine:~/milvus# cat query_collection_data.py 
# -*- coding: utf-8 -*-
import argparse
from pymilvus import connections, Collection

def main():
    parser = argparse.ArgumentParser(description="Query Milvus collection data")
    parser.add_argument(
        "-c", "--collection",
        type=str,
        required=True,
        help="The name of the collection to query"
    )
    args = parser.parse_args()

    collection_name = args.collection

    # 连接 Milvus
    connections.connect("default", host="localhost", port="19530")

    # 加载集合
    collection = Collection(collection_name)
    collection.load()

    # 查询前 100 条数据
    results = collection.query(
        expr="",
        output_fields=["id", "title", "embedding"],  # 请根据你的实际字段调整
        limit=100
    )

    print(f"Data in collection '{collection_name}':")
    for item in results:
        print(f"ID: {item['id']}, Title: {item['title']}, Vector dimension: {len(item['embedding'])}")

if __name__ =="__main__":
    main()
    
#执行脚本
root@huqi-virtual-machine:~/milvus# python3 query_collection_data.py --collection product_8d_collection
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at schema.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at common.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at milvus.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at rg.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at feder.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
/usr/local/lib/python3.10/dist-packages/google/protobuf/runtime_version.py:98: UserWarning: Protobuf gencode version 5.27.2 is exactly one major version older than the runtime version 6.31.1 at msg.proto. Please update the gencode to avoid compatibility violations in the next runtime release.
  warnings.warn(
Data in collection 'product_8d_collection':
ID: 459465252515875228, Title: iPhone 13 Pro, Vector dimension: 8
ID: 459465252515875229, Title: Samsung S23, Vector dimension: 8
ID: 459465252515875230, Title: Huawei Mate60, Vector dimension: 8
ID: 459465252515875231, Title: iPhone 15 Pro Max, Vector dimension: 8

✨ 只写原创,不接广告,不接广告,不接广告。

在这里,你将看到全新的技术分享、运维经验、以及最新的行业动态。我们坚信,原创内容才是最有价值的资源,所以所有文章都是独立创作,与你们一起成长。

💡 下期想学习什么技术?

如果你有任何学习需求或者感兴趣的技术话题,欢迎私信告诉我!我会根据大家的反馈选择下期的内容,帮助你们提升技能。

声明:来自IT运维大爆炸,仅代表创作者观点。链接:https://eyangzhen.com/1591.html

IT运维大爆炸的头像IT运维大爆炸

相关推荐

关注我们
关注我们
购买服务
购买服务
返回顶部