【自然语言处理与大模型】向量数据库:Milvus使用指南

Milvus 是一个开源的向量数据库,Milvus Lite 是 Milvus 向量数据库的轻量级版本,能为 AI 应用提供向量相似性搜索功能。它非常适合用于快速原型开发、资源有限的环境。

安装

bash 复制代码
# 安装 milvus 要求Python 3.8+
pip install "pymilvus[model]"

使用

python 复制代码
from pymilvus import MilvusClient
from pymilvus import model



# 创建一个客户端
client = MilvusClient("./milvus_demo.db")  # 指定一个存储所有数据的文件路径

# 加载本地的词嵌入向量模型
"""
如果你安装了,model依赖则默认值为all-MiniLM-L6-v2
"""
sentence_transformer_ef = model.dense.SentenceTransformerEmbeddingFunction(
    model_name='all-MiniLM-L6-v2', # 指定模型路径
    device='cpu' # 指定要使用的设备,例如"cpu"或"cuda:0"
)


# 创建一个集合
# 检查名为"demo_collection"的集合是否存在
if client.has_collection(collection_name="demo_collection"):
    # 如果存在则删除该集合
    client.drop_collection(collection_name="demo_collection")

client.create_collection(
    collection_name="demo_collection",
    dimension=768,  # 指定向量的维度
)

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 = sentence_transformer_ef.encode_documents(docs)

# 打印embedding后的文档
print("Embeddings:", vectors)
print("Dim:", sentence_transformer_ef.dim, vectors[0].shape)

data = [
    {"id": i, "vector": vectors[i], "text": docs[i], "subject": "history"} 
    for i in range(len(docs))
]




# 插:将数据插入向量数据库
client.insert("demo_collection", data)



# 查:search相似度搜索 或 query关键字匹配
res = client.search(
    collection_name="demo_collection",
    data=[vectors[0]],
    filter="subject == 'history'",   # 过滤条件
    limit=2,  # 最相似的2条
    output_fields=["text", "subject"]
)
print(res)

res = client.query(
    collection_name="demo_collection",
    filter="subject == 'history'",     # 过滤条件
    output_fields=["text", "subject"]  # 只展示的字段
)
print(res)




# 改:修改其中id=1文档
update_docs = ["Artificial intelligence research began in mid-20th century"]
update_vectors = sentence_transformer_ef.encode_documents(update_docs)
update_data = [{
    "id": 1,  # 指定要更新的文档ID
    "text": "Artificial intelligence research began in mid-20th century",  # 新文本
    "vector": update_vectors[0],   # 新向量
    "subject": "computer_science"  # 新分类
}]
res = client.upsert(
    collection_name="demo_collection",
    data=[update_data]  # 注意数据需要是列表格式
)
print(res)




# 删:删除一个文档
res = client.delete(
    collection_name="demo_collection",
    filter="subject == 'history'"  # 过滤条件
)
print(res)

更多案例教学可以查看官方的教程:

Milvus官方文档https://milvus.io/docs/zh/quickstart.md

相关推荐
海宇大数据2 分钟前
零信任架构实战:基于海宇对外投资历史查询服务构建自动化企业图谱投资聚合网关
数据库·人工智能·架构·自动化
Wellijohn5 分钟前
从 Prompt 到 Agent:手写一个能跑起来的最小 RAG Agent
人工智能·llm·agent
AAA修煤气灶刘哥6 分钟前
美团把数据研发的 20 多次操作收进 5 个命令,Agent 怎么过上线这一关?
人工智能·后端·agent
Csvn7 分钟前
WorkBuddy 使用指南:让 AI 记住规则,而不是记住秘密
人工智能
D_C_tyu7 分钟前
AI能力测试·PRD文档分享 | 沉浸式海底世界HTML页面
前端·人工智能·html
极客先躯20 分钟前
智能体开发高级面试每日一题|2026-05-23|什么是 AI Agent?它和普通 LLM 应用有什么区别?
人工智能·面试·职场和发展·高级面试·智能体开发
前端御书房24 分钟前
把 GPT-SoVITS 装进桌面:不用云、不排队,VoiceSmith 上手记
人工智能·gpt·学习·ai
IvorySQL26 分钟前
从数据到智能:PostgreSQL 在医疗垂类智能体与 AI 平台中的核心实践
数据库·人工智能·postgresql
峯58035 分钟前
机器学习概览
人工智能·机器学习
落798.36 分钟前
FusedInferAttentionScore 源码解析(三):从 Tiling Key 到 AI Core,Attention 的设备侧执行骨架
人工智能·cann·ops-transformer