第17篇:基于Milvus的性能测试与代码实现

随着人工智能和大数据技术的快速发展,高效的向量检索系统成为了许多应用的核心组件。Milvus作为一个开源的向量数据库,专为处理大规模、高维向量数据的检索而设计。在实际应用中,评估Milvus的性能是非常重要的一环。本文将详细介绍如何对Milvus进行性能测试与基准,包括确定性能指标、基准测试方法和输出测试效果图片。

一、性能测试指标

在进行性能测试时,首先需要确定合理的性能指标。常见的性能测试指标包括:

  1. 查询时间(Query Time): 测量执行一次查询所需的时间。
  2. 吞吐量(Throughput): 单位时间内能够处理的查询数量。
  3. 延迟(Latency): 查询的响应时间,通常关注P95、P99等高百分位延迟。
  4. 检索精度(Recall): 检索结果中正确结果的比例。
  5. 内存使用(Memory Usage): 系统在运行过程中的内存占用情况。
  6. 存储使用(Storage Usage): 数据库存储向量数据所占用的存储空间。
  7. CPU使用率(CPU Usage): 系统在运行过程中的CPU占用情况。

这些指标能够全面评估Milvus在不同场景下的性能表现。

1.1 指标说明

查询时间(Query Time)

查询时间是衡量数据库在处理单个查询时所需的时间。它直接反映了数据库的响应速度。

吞吐量(Throughput)

吞吐量表示单位时间内数据库能够处理的查询数量,是衡量数据库并发处理能力的重要指标。

延迟(Latency)

延迟是指查询从发出到接收响应所需的时间。高百分位延迟(如P95、P99)反映了系统在高负载下的响应时间。

检索精度(Recall)

检索精度衡量检索结果中正确结果的比例,是衡量向量检索系统准确性的重要指标。

内存使用(Memory Usage)

内存使用反映系统在运行过程中的内存消耗情况,影响系统的稳定性和可扩展性。

存储使用(Storage Usage)

存储使用反映数据库存储向量数据所占用的存储空间,影响数据存储的成本。

CPU使用率(CPU Usage)

CPU使用率反映系统在运行过程中的CPU资源消耗情况,影响系统的处理能力和响应速度。

二、基准测试方法

基准测试是评估数据库性能的重要手段。针对Milvus的基准测试方法包括数据准备、测试环境配置、测试工具选择和测试方案设计等步骤。

2.1 数据准备

基准测试需要使用真实或模拟的数据集。常见的数据集包括SIFT1M、DEEP1B等,这些数据集涵盖了不同规模和维度的向量数据。

数据集下载

可以通过以下脚本下载SIFT1M数据集:

wget ftp://ftp.irisa.fr/local/texmex/corpus/sift.tar.gz
tar -xvzf sift.tar.gz

2.2 测试环境配置

测试环境包括硬件配置、操作系统和Milvus服务器的配置。以下是一个典型的测试环境配置示例:

硬件配置
  • CPU:Intel Xeon E5-2680 v4
  • 内存:128GB
  • 存储:SSD 1TB
软件配置
  • 操作系统:Ubuntu 20.04
  • Milvus版本:2.0.0
  • Python版本:3.8

2.3 测试工具选择

常用的基准测试工具包括Milvus自带的Benchmark工具和第三方测试工具。本文将使用Milvus Benchmark工具进行测试。

安装Milvus Benchmark工具
pip install pymilvus
pip install milvus-benchmark

2.4 测试方案设计

测试方案设计包括测试场景、测试指标和测试步骤等内容。以下是一个基准测试方案设计示例:

测试场景
  1. 插入性能测试:测试Milvus在不同规模数据集下的插入性能。
  2. 检索性能测试:测试Milvus在不同查询负载下的检索性能。
  3. 内存和存储使用测试:测试Milvus在不同规模数据集下的内存和存储使用情况。
测试步骤
  1. 启动Milvus服务器并配置数据库。
  2. 加载数据集并进行向量插入测试。
  3. 执行检索查询并记录查询时间、延迟和吞吐量。
  4. 监控内存和存储使用情况。
  5. 分析测试结果并输出测试报告。

三、基于Milvus的性能测试与基准

3.1 数据加载和插入性能测试

首先,我们将进行数据加载和插入性能测试。以下是详细的代码实现:

from pymilvus import connections, Collection, CollectionSchema, FieldSchema, DataType
import numpy as np
import time

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

# 定义集合的字段
fields = [
    FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=True),
    FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=128)
]

# 创建集合
schema = CollectionSchema(fields, "SIFT1M dataset collection")
collection = Collection("sift1m_collection", schema)

# 加载数据集
data = np.load("sift1m.npy")

# 插入数据并记录时间
start_time = time.time()
collection.insert(data)
end_time = time.time()

print(f"Data insertion time: {end_time - start_time} seconds")
流程图:
连接Milvus服务器
定义集合字段
创建集合
加载数据集
插入数据并记录时间
输出插入时间

3.2 检索性能测试

接下来,我们将进行检索性能测试。以下是详细的代码实现:

from pymilvus import Collection
import numpy as np
import time

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

# 加载集合
collection = Collection("sift1m_collection")

# 随机生成查询向量
query_vector = np.random.random((1, 128)).astype(np.float32)

# 设置检索参数
search_params = {"metric_type": "L2", "params": {"nprobe": 10}}

# 执行检索并记录时间
start_time = time.time()
results = collection.search(query_vector, "embedding", search_params, limit=10)
end_time = time.time()

print(f"Query time: {end_time - start_time} seconds")
print(f"Search results: {results}")
流程图:
连接Milvus服务器
加载集合
生成查询向量
设置检索参数
执行检索并记录时间
输出查询时间和检索结果

3.3 内存和存储使用测试

在进行性能测试的同时,我们还需要监控系统的内存和存储使用情况。以下是详细的代码实现:

import psutil
import os

# 获取内存使用情况
memory_info = psutil.virtual_memory()
print(f"Memory usage: {memory_info.percent}%")

# 获取存储使用情况
storage_info = psutil.disk_usage('/')
print(f"Storage usage: {storage_info.percent}%")

3.4 完整性能测试脚本

以下是一个完整的性能测试脚本,包括数据加载、插入性能测试、检索性能测试和内存、存储使用测试:

import numpy as np
import time
import psutil
from pymilvus import connections, Collection, CollectionSchema, FieldSchema, DataType

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

# 定义集合的字段
fields = [
    FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=True),
    FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=128)
]

# 创建集合
schema = CollectionSchema(fields, "SIFT1M dataset collection")
collection = Collection("sift1m_collection", schema)

# 加载数据集
data = np.load("sift1m.npy")

# 插入数据并记录时间
start_time = time.time()
collection.insert

(data)
end_time = time.time()

print(f"Data insertion time: {end_time - start_time} seconds")

# 随机生成查询向量
query_vector = np.random.random((1, 128)).astype(np.float32)

# 设置检索参数
search_params = {"metric_type": "L2", "params": {"nprobe": 10}}

# 执行检索并记录时间
start_time = time.time()
results = collection.search(query_vector, "embedding", search_params, limit=10)
end_time = time.time()

print(f"Query time: {end_time - start_time} seconds")
print(f"Search results: {results}")

# 获取内存使用情况
memory_info = psutil.virtual_memory()
print(f"Memory usage: {memory_info.percent}%")

# 获取存储使用情况
storage_info = psutil.disk_usage('/')
print(f"Storage usage: {storage_info.percent}%")

四、测试效果图片

为了更好地展示测试效果,可以生成相应的图表。以下是使用Matplotlib生成测试效果图的示例代码:

4.1 生成插入性能图表

import matplotlib.pyplot as plt

# 数据插入时间
insertion_times = [end_time - start_time for _ in range(10)]  # 假设进行了10次插入测试
plt.figure(figsize=(10, 5))
plt.plot(insertion_times, label="Insertion Time")
plt.xlabel("Test Iterations")
plt.ylabel("Time (seconds)")
plt.title("Data Insertion Performance")
plt.legend()
plt.show()

4.2 生成检索性能图表

# 查询时间
query_times = [end_time - start_time for _ in range(10)]  # 假设进行了10次检索测试
plt.figure(figsize=(10, 5))
plt.plot(query_times, label="Query Time")
plt.xlabel("Test Iterations")
plt.ylabel("Time (seconds)")
plt.title("Query Performance")
plt.legend()
plt.show()

4.3 生成内存和存储使用图表

# 内存使用情况
memory_usages = [psutil.virtual_memory().percent for _ in range(10)]  # 假设监控了10次
# 存储使用情况
storage_usages = [psutil.disk_usage('/').percent for _ in range(10)]  # 假设监控了10次

plt.figure(figsize=(10, 5))
plt.plot(memory_usages, label="Memory Usage (%)")
plt.plot(storage_usages, label="Storage Usage (%)")
plt.xlabel("Test Iterations")
plt.ylabel("Usage (%)")
plt.title("Memory and Storage Usage")
plt.legend()
plt.show()

五、总结

本文详细介绍了基于Milvus的性能测试与基准,包括确定性能指标、基准测试方法和测试效果的可视化。通过合理的性能测试,可以全面评估Milvus在不同场景下的性能表现,从而指导系统的优化和改进。希望本文对大家理解和实施性能测试有所帮助。
通过上述流程和代码示例,可以高效地进行Milvus的性能测试与基准评估,确保系统在实际应用中的高效稳定运行。

如果你喜欢这篇文章,别忘了收藏文章、关注作者、订阅专栏,感激不尽。

  • 28
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
基于 Milvus 的多模态检索系统可以实现对多种类型数据的检索,例如图像、文本、语音等。下面是一个简单的演示: 1. 首先,需要安装 Milvus 和相应的 Python SDK: ```shell pip install pymilvus==2.0.0rc5 pip install opencv-python==4.5.1.48 pip install Pillow==8.2.0 pip install grpcio==1.32.0 pip install grpcio-tools==1.32.0 ``` 2. 接下来,我们需要准备一些数据。这里以图像为例,将一些图像文件存储在本地文件夹中。 3. 然后,我们需要将这些图像向量化,并将它们插入到 Milvus 中。这里使用 ResNet50 模型提取图像特征,并使用 Milvus Python SDK 将特征向量插入到 Milvus 中。 ```python import os import cv2 import numpy as np from PIL import Image from milvus import Milvus, IndexType, MetricType, Status # 连接 Milvus milvus = Milvus(host='localhost', port='19530') # 创建 collection collection_name = 'image_collection' if collection_name in milvus.list_collections(): milvus.drop_collection(collection_name) milvus.create_collection(collection_name, {'fields': [ {'name': 'id', 'type': 'int64', 'is_primary': True}, {'name': 'embedding', 'type': 'float', 'params': {'dim': 2048}} ], 'segment_row_limit': 4096, 'auto_id': False}) # 加载 ResNet50 模型 model = cv2.dnn.readNetFromTorch('resnet50.t7') model.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV) model.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU) # 提取图像特征并插入到 Milvus 中 data_path = 'image_data' for i, file_name in enumerate(os.listdir(data_path)): file_path = os.path.join(data_path, file_name) img = cv2.imread(file_path) img = cv2.resize(img, (224, 224)) blob = cv2.dnn.blobFromImage(img, 1, (224, 224), (104, 117, 123)) model.setInput(blob) embedding = model.forward().flatten() status, ids = milvus.insert(collection_name=collection_name, records=[ {'id': i, 'embedding': embedding.tolist()} ]) print(f'Insert image {file_name} with id {ids[0]}') # 创建索引 milvus.create_index(collection_name, IndexType.IVF_FLAT, {'nlist': 128}) ``` 4. 现在,我们已经将图像向量化并插入到 Milvus 中了。接下来,我们可以使用 Milvus 的向量相似度搜索功能来实现多模态检索。这里以图像检索为例,给定一张查询图像,我们可以使用同样的方式提取其特征向量,并在 Milvus 中搜索与其相似的图像。 ```python # 加载查询图像 query_path = 'query_image.jpg' query_img = cv2.imread(query_path) query_img = cv2.resize(query_img, (224, 224)) query_blob = cv2.dnn.blobFromImage(query_img, 1, (224, 224), (104, 117, 123)) # 提取查询图像特征 model.setInput(query_blob) query_embedding = model.forward().flatten() # 在 Milvus 中搜索相似的图像 search_param = {'nprobe': 16} status, results = milvus.search(collection_name, query_embedding.tolist(), 10, search_params=search_param) print(f'Search results: {results}') ``` 以上就是一个简单的基于 Milvus 的多模态检索系统的演示。除了图像检索,我们也可以使用类似的方式实现文本、语音等多种类型数据的检索。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Gemini技术窝

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

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

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

打赏作者

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

抵扣说明:

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

余额充值