大语言模型学习--向量数据库Milvus实践

Milvus是目前比较流行的开源向量数据库,其官网地址

Milvus 是什么? | Milvus 文档

1.Milvus简介

Milvus 是一种高性能、高扩展性的向量数据库。Milvus 提供强大的数据建模功能,能够将非结构化或多模式数据组织成结构化的 Collections。它支持多种数据类型,适用于不同的属性模型,包括常见的数字和字符类型、各种向量类型、数组、集合和 JSON。

Milvus 提供三种部署模式

  • Milvus Lite 是一个 Python 库,可以轻松集成到您的应用程序中。作为 Milvus 的轻量级版本,它非常适合在 Jupyter Notebooks 中进行快速原型开发,或在资源有限的边缘设备上运行。
  • Milvus Standalone 是单机服务器部署,所有组件都捆绑在一个 Docker 镜像中,方便部署。
  • Milvus Distributed 可部署在 Kubernetes 集群上,采用云原生架构,专为十亿规模甚至更大的场景而设计。该架构可确保关键组件的冗余。

Milvus 的云原生和高度解耦的系统架构

2.Milvus实践

推荐一个在线python运行环境(再也不用本地windows安装linux虚拟机了)

玻尔 | 全球科学家的 AI for Science 空间站

下面使用Milvus Lite本地实践一下,Milvus Lite,它是pymilvus 中包含的一个 python 库,可以嵌入到客户端应用程序中。

安装Milvus

复制代码
pip install -U pymilvus

设置向量数据库

复制代码
from pymilvus import MilvusClient
client = MilvusClient("milvus_demo.db")

创建Collections

复制代码
if client.has_collection(collection_name="demo_collection"):
    client.drop_collection(collection_name="demo_collection")
client.create_collection(
    collection_name="demo_collection",
    dimension=768,  # The vectors we will use in this demo has 768 dimensions
)

用向量表示文本

复制代码
import random

docs = [
    "Artificial intelligence was founded as an academic discipline in 1956.",
    "Alan Turing was the first person to conduct substantial research in AI.",
    "Born in Maida Vale, London, Turing was raised in southern England.",
]
vectors = [[random.uniform(-1, 1) for _ in range(768)] for _ in docs]
data = [
    {"id": i, "vector": vectors[i], "text": docs[i], "subject": "history"}
    for i in range(len(vectors))
]

print("Data has", len(data), "entities, each with fields: ", data[0].keys())
print("Vector dim:", len(data[0]["vector"]))

插入数据

复制代码
res = client.insert(collection_name="demo_collection", data=data)

print(res)

向量搜索

复制代码
# query_vectors = embedding_fn.encode_queries(["Who is Alan Turing?"])
# If you don't have the embedding function you can use a fake vector to finish the demo:
query_vectors = [ [ random.uniform(-1, 1) for _ in range(768) ] ]
res = client.search(
    collection_name="demo_collection",  # target collection
    data=query_vectors,  # query vectors
    limit=2,  # number of returned entities
    output_fields=["text", "subject"],  # specifies fields to be returned
)
print(res)

其他一些操作可以参考官网文档

管理数据库 | Milvus 文档

相关推荐
CoderJia程序员甲6 小时前
GitHub 热榜项目 - 日榜(2026-03-29)
人工智能·ai·大模型·github·ai教程
王小义笔记14 小时前
大模型微调步骤与精髓总结
python·大模型·llm
CoderJia程序员甲15 小时前
GitHub 热榜项目 - 日榜(2026-03-30)
人工智能·ai·大模型·github·ai教程
hhzz17 小时前
Claude Code 实战---开发华尔街日报风格新闻卡片应用
人工智能·大模型·智能体开发·ai编程工具
core51217 小时前
赋予AI真正的“长期记忆”:开源大模型记忆操作系统 MemOS 深度解析与实战
人工智能·开源·大模型·记忆·长期记忆·memos
Flying pigs~~17 小时前
基于Bert的模型迁移文本分类项目
人工智能·深度学习·算法·大模型·nlp·bert
再不会python就不礼貌了1 天前
从工具到个人助理——AI Agent的原理、演进与安全风险
人工智能·安全·ai·大模型·transformer·ai编程
有为少年1 天前
告别“唯语料论”:用合成抽象数据为大模型开智
人工智能·深度学习·神经网络·算法·机器学习·大模型·预训练
张彦峰ZYF1 天前
大模型LLM ACA - ACP认证考试模拟试卷二
大模型·llm·aca - acp
*JOKER1 天前
Flow Matching&生成算法
人工智能·深度学习·机器学习·大模型·生成模型·flow matching