milvus lite快速实践

milvus lite快速实践

Milvus Lite 是Milvus 的轻量级版本,Milvus 是一个开源向量数据库,通过向量嵌入和相似性搜索为人工智能应用提供支持,最典型的应用场景就是 RAG(Retrieval-Augmented Generation,检索增强生成),为 RAG 系统提供了强大的向量存储和检索能力。

通过下面的实践,可以了解文本向量化与相似度匹配(语义匹配)的大概过程,了解RAG落地背后的机制。

安装 milvus lite

Milvus Lite 已包含在Milvus 的 Python SDK 中。它可以通过pip install pymilvus 简单地部署。

部署前提:

  • python 3.8+;
  • Ubuntu >= 20.04(x86_64 或者 arm64)
  • MacOS >= 11.0(苹果 M1/M2 或者 x86_64)

安装命令如下:

pip install -U pymilvus

文本向量化

创建向量数据库

通过实例化MilvusClient ,指定一个存储所有数据的文件名来创建本地的Milvus向量数据库。例如下:

from pymilvus import MilvusClient

client = MilvusClient("milvus_demo.db")

创建 Collections

Collections类似于传统 SQL 数据库中的表格。在 Milvus 中Collections 用来存储向量及其相关元数据。创建 Collections 时,可以定义 Schema 和索引参数来配置向量规格,如维度、索引类型和远距离度量。

创建 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,  # 该demo中的向量规格为768维
)

文本向量化

下载 embedding模型 为测试的文本生成向量。

首先,安装模型库,该软件包包含 PyTorch 等基本 ML 工具。如果本地环境从未安装过 PyTorch,则软件包下载可能需要一些时间。

pip install "pymilvus[model]"

用默认模型生成向量 Embeddings。Milvus 希望数据以字典列表的形式插入,每个字典代表一条数据记录,称为实体

from pymilvus import model

# 如果访问 https://huggingface.co/ 失败,请取消注释以下路径
# import os
# os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'

# 这将下载一个较小的嵌入模型 "paraphrase-albert-small-v2"(~50MB)。
embedding_fn = model.DefaultEmbeddingFunction()

# 用来搜索的文本字符串
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 = embedding_fn.encode_documents(docs)

# 输出向量有768维,与创建的集合匹配。
print("Dim:", embedding_fn.dim, vectors[0].shape)  # Dim: 768 (768,)


# 每个实体(entity)都有 id、向量表示、原始文本和主题标签,用于演示元数据过滤。
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"]))

输出:

Dim: 768 (768,)
Data has 3 entities, each with fields:  dict_keys(['id', 'vector', 'text', 'subject'])
Vector dim: 768

插入数据

下面把把数据插入 Collections 中:

res = client.insert(collection_name="demo_collection", data=data)

print(res)

输出:

{'insert_count': 3, 'ids': [0, 1, 2], 'cost': 0}

语义搜索

现在我们可以通过将搜索查询文本表示为向量来进行语义搜索,并在 Milvus 上进行向量相似性搜索。

向量搜索

Milvus 可同时接受一个或多个向量搜索请求。query_vectors 变量的值是一个向量列表,其中每个向量都是一个浮点数数组。

query_vectors = embedding_fn.encode_queries(["Who is Alan Turing?"])

res = client.search(
    collection_name="demo_collection",  # 目标 collection
    data=query_vectors,  # query vectors 查询的向量
    limit=2,  # 返回的entity数量
    output_fields=["text", "subject"],  # 指定查询返回的实体字段
)

print(res)

输出:

data: ["[{'id': 2, 'distance': 0.5859944820404053, 'entity': {'text': 'Born in Maida Vale, London, Turing was raised in southern England.', 'subject': 'history'}}, {'id': 1, 'distance': 0.5118255615234375, 'entity': {'text': 'Alan Turing was the first person to conduct substantial research in AI.', 'subject': 'history'}}]"] , extra_info: {'cost': 0}

输出结果是一个结果列表,每个结果映射到一个向量搜索查询。每个查询都包含一个结果列表,其中每个结果都包含实体主键、到查询向量的距离以及指定output_fields 的实体详细信息。

从distance值可以评估搜索结果的相关度,越接近0,则搜索结果更相关。关于相似度量更多说明,请参考相似度量

带元数据过滤的向量搜索

你还可以在考虑元数据值(在 Milvus 中称为 "标量 "字段,因为标量指的是非向量数据)的同时进行向量搜索。这可以通过指定特定条件的过滤表达式来实现。让我们在下面的示例中看看如何使用subject 字段进行搜索和筛选。

# 在另外一个主题中插入更多文档。
docs = [
    "Machine learning has been used for drug design.",
    "Computational synthesis with AI algorithms predicts molecular properties.",
    "DDR1 is involved in cancers and fibrosis.",
]
vectors = embedding_fn.encode_documents(docs)
data = [
    {"id": 3 + i, "vector": vectors[i], "text": docs[i], "subject": "biology"}
    for i in range(len(vectors))
]

client.insert(collection_name="demo_collection", data=data)

# 通过filter过滤subject。这将排除任何主题为“历史”的文本,尽管与查询向量非常接近。
res = client.search(
    collection_name="demo_collection",
    data=embedding_fn.encode_queries(["tell me AI related information"]),
    filter="subject == 'biology'",
    limit=2,
    output_fields=["text", "subject"],
)

print(res)

输出:

data: ["[{'id': 4, 'distance': 0.27030569314956665, 'entity': {'text': 'Computational synthesis with AI algorithms predicts molecular properties.', 'subject': 'biology'}}, {'id': 3, 'distance': 0.16425910592079163, 'entity': {'text': 'Machine learning has been used for drug design.', 'subject': 'biology'}}]"] , extra_info: {'cost': 0}

默认情况下,标量字段不编制索引。如果需要在大型数据集中执行元数据过滤搜索,可以考虑使用固定 Schema,同时打开索引以提高搜索性能。

除了向量搜索,还可以执行其他类型的搜索。

查询

查询()是一种操作符,用于检索与某个条件(如过滤表达式或与某些 id 匹配)相匹配的所有实体。

例如,检索标量字段具有特定值的所有实体:

res = client.query(
    collection_name="demo_collection",
    filter="subject == 'history'",
    output_fields=["text", "subject"],
)

通过主键直接检索实体

res = client.query(
    collection_name="demo_collection",
    ids=[0, 2],
    output_fields=["vector", "text", "subject"],
)

删除实体

如果想清除数据,可以删除指定主键的实体,或删除与特定过滤表达式匹配的所有实体。

# 使用主键删除实体。
res = client.delete(collection_name="demo_collection", ids=[0, 2])

print(res)

# 使用filter 表达式删除所有 subject 为 "biology" 的实体。
res = client.delete(
    collection_name="demo_collection",
    filter="subject == 'biology'",
)

print(res)

输出:

[0, 2]
[3, 4, 5]

加载现有数据

由于 Milvus Lite 的所有数据都存储在本地文件中,因此即使在程序终止后,你也可以通过创建一个带有现有文件的MilvusClient ,将所有数据加载到内存中。例如,这将恢复 "milvus_demo.db "文件中的 Collections,并继续向其中写入数据。

from pymilvus import MilvusClient

client = MilvusClient("milvus_demo.db")

删除 Collections

如果想删除某个 Collections 中的所有数据,可以通过以下方法丢弃该 Collections

# 删除 Collections
client.drop_collection(collection_name="demo_collection")

参考资料

  1. https://milvus.io/docs/zh/quickstart.md

  2. https://milvus.io/docs/zh/milvus_lite.md

完整代码:

from pymilvus import model
from pymilvus import MilvusClient

# 一、 创建向量数据库和集合
# 通过实例化`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,  # 该demo中的向量规格为768维
)


# 二、 文本向量化
# 如果访问 https://huggingface.co/ 失败,请取消注释以下路径
# import os
# os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'

# 这将下载一个较小的嵌入模型 "paraphrase-albert-small-v2"(~50MB)。
embedding_fn = model.DefaultEmbeddingFunction()

# 用来搜索的文本字符串
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 = embedding_fn.encode_documents(docs)

# 输出向量有768维,与创建的集合匹配。
print("Dim:", embedding_fn.dim, vectors[0].shape)  # Dim: 768 (768,)


# 每个实体(entity)都有 id、向量表示、原始文本和主题标签,用于演示元数据过滤。
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("----------------------将数据插入到集合中-----------------------------")
print(res)

# 三、 向量搜索
print("-------------------向量搜索-----------------------------------------")
query_vectors = embedding_fn.encode_queries(["Who is Alan Turing?"])

res = client.search(
    collection_name="demo_collection",  # 目标 collection
    data=query_vectors,  # query vectors 查询的向量
    limit=2,  # 返回的entity数量
    output_fields=["text", "subject"],  # 指定查询返回的实体字段
)

print(res)

# 带元数据过滤的搜索
docs = [
    "Machine learning has been used for drug design.",
    "Computational synthesis with AI algorithms predicts molecular properties.",
    "DDR1 is involved in cancers and fibrosis.",
]
vectors = embedding_fn.encode_documents(docs)
data = [
    {"id": 3 + i, "vector": vectors[i], "text": docs[i], "subject": "biology"}
    for i in range(len(vectors))
]

client.insert(collection_name="demo_collection", data=data)

# 通过filter过滤subject。这将排除任何主题为“历史”的文本,尽管与查询向量非常接近。
print("----------------向量搜索,打印subject为biology的搜索结果----------------------")
res = client.search(
    collection_name="demo_collection",
    data=embedding_fn.encode_queries(["tell me AI related information"]),
    filter="subject == 'biology'",
    limit=2,
    output_fields=["text", "subject"],
)
print(res)

# 四、 查询
# 检索标量字段具有特定值的所有实体:
print("--------------查询,检索标量字段具有特定值为history的所有实体:---------------")
res = client.query(
    collection_name="demo_collection",
    filter="subject == 'history'",
    output_fields=["text", "subject"],
)
print(res)

# 通过主键值检索实体:
print("--------------------查询,过主键值检索实体:--------------------------------")
res = client.query(
    collection_name="demo_collection",
    ids=[0, 2],
    output_fields=["vector", "text", "subject"],
)
print(res)

# 使用主键删除实体。
print("--------------------------使用主键删除实体:-------------------------------")
res = client.delete(collection_name="demo_collection", ids=[0, 2])
print(res)

# 使用filter 表达式删除所有 subject 为 "biology" 的实体。
print("-----------filter 表达式删除所有 subject为 biology的实体。:----------------")
res = client.delete(
    collection_name="demo_collection",
    filter="subject == 'biology'",
)

print(res)

# 五、 删除集合
client.drop_collection(collection_name="demo_collection")

### Milvus Lite 版本介绍 Milvus Lite 是一款轻量级的开源向量数据库,旨在简化用户的初次体验和小型项目的开发过程。此版本适合希望快速上手而不必担心复杂配置的新用户。自版本 2.4.2 起,`pymilvus` 包已经包含了 Milvus Lite 组件[^1]。 对于那些只需要处理不超过一百万条记录的应用场景而言,Milvus Lite 提供了一种便捷的方式来探索 Milvus 功能集的可能性。它特别适用于 AI 应用程序的早期原型设计阶段,在这个时期更关注的是功能验证而非最终产品的性能优化[^3]。 ### 安装方法 为了获得最新的 Milvus Lite 发布版,可以通过 Python 的包管理工具 `pip` 来完成安装: ```bash pip install -U pymilvus ``` 这条命令不仅会更新或安装 `pymilvus` 到最新稳定版本,还会自动拉取必要的依赖项以支持 Milvus Lite 的运行环境[^2]。 ### 使用指南 一旦成功安装了 `pymilvus` 和内置的 Milvus Lite 后,便可以开始创建连接实例并与之交互。下面是一个简单的例子展示如何初始化一个本地模式下的客户端对象,并执行基本的操作如插入数据点、建立索引以及查询最近邻节点等: ```python from pymilvus import connections, FieldSchema, CollectionSchema, DataType, Collection # 连接到本地部署的 Milvus 实例,默认监听 localhost:19530 地址 connections.connect("default") fields = [ FieldSchema(name="id", dtype=DataType.INT64, is_primary=True), FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=8) ] schema = CollectionSchema(fields) collection_name = "example_collection" milvus_lite_colletion = Collection( name=collection_name, schema=schema ) data_points = [[i for i in range(10)], [[float(i)] * 8 for i in range(10)]] milvus_lite_colliction.insert(data_points) index_params = {"metric_type": "L2", "index_type": "IVF_FLAT", "params": {"nlist": 128}} milvus_lite_colliction.create_index(field_name="embedding", index_params=index_params) search_param = {"metric_type": "L2", "params": {"nprobe": 10}} results = milvus_lite_colliction.search([[0.] * 8], param=search_param, limit=3) print(results) ``` 这段代码展示了怎样定义集合结构、加载测试数据、设置索引参数并发起一次近似最近邻居搜索请求的过程[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lldhsds

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值