前言
用的milvus版本为2.3.7。
遇到的问题:
collection.query(expr=“”, output_fields=[“count(*)”]) 和 collection.query_iterator迭代后条数不一致
下面的统计的完整代码:
# milvus_consistency_check.py
# 用于验证 Milvus 中 count(*) 与 query_iterator 的数据一致性
from pymilvus import connections, Collection
import time
# ==================== 配置 ====================
MILVUS_HOST = "127.0.0.1" # 修改为你的 Milvus 地址
MILVUS_PORT = 19530 # 默认端口
COLLECTION_NAME = "test_collection" # 修改为你的集合名
DB_NAME = "your_db"
BATCH_SIZE = 1000
# ==================== 获取 count(*) ====================
def get_count_star(collection):
try:
res = collection.query(expr="", output_fields=["count(*)"])
return res[0]["count(*)"]
except Exception as e:
print(f"❌ count(*) 查询失败: {
e}")
raise
# ==================== 获取 query_iterator 真实条数 ====================
def get_query_iterator_count(collection):
try:
# 创建迭代器(必须指定 output_fields)
it = collection.query_iterator(
expr="",
batch_size=BATCH_SIZE,
output_fields=["id"] # 只需要 id 字段即可计数
)
count = 0
batch_count = 0
while True:
result = it.next()
if not result:
break
count += len(result)
batch_count += 1
print(f" 批次 {
batch_count}: 读取 {
len(result)} 条,累计 {
count}")
it.close()

最低0.47元/天 解锁文章
2531

被折叠的 条评论
为什么被折叠?



