跳到主要内容
版本:v2.4.x

使用迭代器

Milvus 提供搜索和查询迭代器,用于迭代大量实体。由于 Milvus 将 TopK 限制在 16384,用户可以使用迭代器以批处理模式返回大量甚至整个 Collection 中的实体。

概述

迭代器是扫描整个 Collection 或通过指定主键值或过滤表达式迭代大量实体的有效工具。与带有偏移限制参数的搜索或查询调用相比,使用迭代器更高效、更可扩展。

使用迭代器的好处

  • 简单:消除了复杂的偏移限制设置。

  • 高效:只获取需要的数据,提供可扩展的数据检索。

  • 一致性通过布尔筛选器确保数据集大小一致。

说明

注释

  • 此功能适用于 Milvus 2.3.x 或更高版本。

准备工作

以下准备步骤连接 Milvus 并将随机生成的实体插入 Collection。

步骤 1:创建 Collection

使用 MilvusClient连接到 Milvus 服务器,并使用 create_collection()来创建 Collection。

使用 MilvusClientV2连接到 Milvus 服务器,并使用 createCollection()创建 Collection。

from pymilvus import MilvusClient

# 1. Set up a Milvus client
client = MilvusClient(
uri="http://localhost:19530"
)

# 2. Create a collection
client.create_collection(
collection_name="quick_setup",
dimension=5,
)

第二步:插入随机生成的实体

使用 insert()将实体插入 Collection。

使用 insert()将实体插入 Collection。

# 3. Insert randomly generated vectors
colors = ["green", "blue", "yellow", "red", "black", "white", "purple", "pink", "orange", "brown", "grey"]
data = []

for i in range(10000):
current_color = random.choice(colors)
current_tag = random.randint(1000, 9999)
data.append({
"id": i,
"vector": [ random.uniform(-1, 1) for _ in range(5) ],
"color": current_color,
"tag": current_tag,
"color_tag": f"{current_color}_{str(current_tag)}"
})

print(data[0])

# Output
#
# {
# "id": 0,
# "vector": [
# -0.5705990742218152,
# 0.39844925120642083,
# -0.8791287928610869,
# 0.024163154953680932,
# 0.6837669917169638
# ],
# "color": "purple",
# "tag": 7774,
# "color_tag": "purple_7774"
# }

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

print(res)

# Output
#
# {
# "insert_count": 10000,
# "ids": [
# 0,
# 1,
# 2,
# 3,
# 4,
# 5,
# 6,
# 7,
# 8,
# 9,
# "(9990 more items hidden)"
# ]
# }

使用迭代器搜索

迭代器使相似性搜索更具可扩展性。

要使用迭代器搜索,请调用search_iterator()方法:

要使用迭代器搜索,请调用searchIterator()方法:

  1. 初始化搜索迭代器,定义搜索参数和输出字段。

  2. 在循环中使用**next()**方法对搜索结果进行分页。

    • 如果该方法返回一个空数组,则循环结束,不再提供更多页面。

    • 所有结果都包含指定的输出字段。

  3. 检索完所有数据后,手动调用**close()**方法关闭迭代器。

from pymilvus import Collection,connections

# 4. Search with iterator
connections.connect(host="127.0.0.1", port=19530)
collection = Collection("quick_setup")

query_vectors = [[0.3580376395471989, -0.6023495712049978, 0.18414012509913835, -0.26286205330961354, 0.9029438446296592]]
search_params = {
"metric_type": "IP",
"params": {"nprobe": 10}
}

iterator = collection.search_iterator(
data=query_vectors,
anns_field="vector",
batch_size=10,
param=search_params,
output_fields=["color_tag"],
limit=300
)
# search 300 entities totally with 10 entities per page

results = []

while True:
result = iterator.next()
if not result:
iterator.close()
break

results.extend(result)

for hit in result:
results.append(hit.to_dict())

print(results)

# Output
#
# [
# {
# "id": 1756,
# "distance": 2.0642056465148926,
# "entity": {
# "color_tag": "black_9109"
# }
# },
# {
# "id": 6488,
# "distance": 1.9437453746795654,
# "entity": {
# "color_tag": "purple_8164"
# }
# },
# {
# "id": 3338,
# "distance": 1.9107104539871216,
# "entity": {
# "color_tag": "brown_8121"
# }
# }
# ]
参数描述
data一个 Embedding 列表。
Milvus 会搜索与指定 Embedding 最相似的 Embedding。
anns_field当前 Collection 中的向量字段名称。
batch_size每次在当前迭代器上调用next() 时要返回的实体数量。
默认值为1000。将其设置为适当的值,以控制每次迭代返回的实体数量。
param该操作符特有的参数设置。
  • metric_type:应用于此操作的度量类型。该类型应与上面指定的向量字段索引时使用的类型相同。可能的值有L2IPCOSINEJACCARDHAMMING
  • params:附加参数。详情请参阅search_iterator()

| | output_fields | 要包含在返回的每个实体中的字段名列表。 默认值为 "无"。如果未指定,则只包含主字段。 | | limit | 要返回的实体总数。 默认值为**-1**,表示将返回所有匹配实体。 |

参数说明
withCollectionName设置 Collection 名称。Collection 名称不能为空或 null。
withVectorFieldName按名称设置目标向量字段。字段名称不能为空或空。
withVectors设置目标向量。最多允许 16384 个向量。
withBatchSize每次在当前迭代器上调用next() 时返回的实体数量。
默认值为1000。将其设置为适当的值,以控制每次迭代返回的实体数量。
withParams以 JSON 格式指定搜索参数。更多信息,请参阅searchIterator()

使用迭代器查询

要使用迭代器查询,请调用query_iterator()方法:

要使用迭代器搜索,请调用queryIterator()方法:

# 6. Query with iterator
iterator = collection.query_iterator(
batch_size=10, # Controls the size of the return each time you call next()
expr="color_tag like \"brown_8\"",
output_fields=["color_tag"]
)

results = []

while True:
result = iterator.next()
if not result:
iterator.close()
break

results.extend(result)

# 8. Check the search results
print(len(results))

print(results[:3])

# Output
#
# [
# {
# "color_tag": "brown_8785",
# "id": 94
# },
# {
# "color_tag": "brown_8568",
# "id": 176
# },
# {
# "color_tag": "brown_8721",
# "id": 289
# }
# ]
参数说明
batch_size每次在当前迭代器上调用next() 时要返回的实体数量。
该值默认为1000。将其设置为合适的值,以控制每次迭代返回的实体数。
expr用于过滤匹配实体的标量过滤条件。
默认值为 "无",表示忽略标量过滤。要创建标量过滤条件,请参阅布尔表达式规则
output_fields要包含在返回的每个实体中的字段名列表。
该值默认为 "无"。如果未指定,则只包含主字段。
limit要返回的实体总数。
默认值为**-1**,表示将返回所有匹配实体。
参数说明
withCollectionName设置 Collection 名称。Collection 名称不能为空或 null。
withExpr设置查询实体的表达式。要建立标量过滤条件,请参阅布尔表达式规则
withBatchSize每次在当前迭代器上调用next() 时要返回的实体数量。
默认值为1000。将其设置为适当的值,以控制每次迭代返回的实体数。
addOutField指定输出标量字段(可选)。