You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Connector通过Query ID获取Snowflake查询的扫描字节数与总耗时

通过Snowflake Python Connector获取指定Query ID的扫描字节数与总耗时

你可以通过查询Snowflake的系统视图,结合已知的Query ID来获取扫描字节数和总耗时。以下是修改后的完整代码:

import snowflake.connector

con = snowflake.connector.connect(
    account="eeeeeeeeee",
    user="xxxxxxxxxxxx",
    password="yyyyyyyyyyy",
    warehouse="zzzzzzzzzzzzz",
    database="dddddddddddddd",
)

try:
    cmd = """
        copy into "DB1"."SCH1"."TB1"
        from s3://bucket1/folder1/ credentials=(aws_key_id='xxxxxxxxxx' aws_secret_key='yyyyyyyyyyyyyyyy')
        file_format = (type = csv field_delimiter = '|' skip_header = 1)
        on_error = 'continue';
    """
    # 执行COPY语句,获取游标列表
    res_list = con.execute_string(cmd)
    # 提取第一个游标的Query ID
    query_id = res_list[0]._sfqid[0]

    # 查询系统视图获取指标
    get_metrics_cmd = f"""
        SELECT 
            BYTES_SCANNED, 
            TOTAL_ELAPSED_TIME,
            -- 可选:转换耗时为秒
            TOTAL_ELAPSED_TIME / 1000 AS TOTAL_ELAPSED_SECONDS
        FROM INFORMATION_SCHEMA.QUERY_HISTORY
        WHERE QUERY_ID = '{query_id}'
    """
    cursor = con.cursor()
    cursor.execute(get_metrics_cmd)
    metrics = cursor.fetchone()

    if metrics:
        bytes_scanned = metrics[0]
        total_duration_ms = metrics[1]
        total_duration_sec = metrics[2]
        print(f"扫描字节数:{bytes_scanned}")
        print(f"总耗时(毫秒):{total_duration_ms}")
        print(f"总耗时(秒):{total_duration_sec}")

    con.commit()
except Exception as e:
    raise e
finally:
    con.close()

关键说明:

  • Query ID获取修正:原代码中的x._sfqid[0]需改为res_list[0]._sfqid[0],因为execute_string返回的是游标对象列表,第一个游标对应COPY语句的执行结果。
  • 系统视图选择:
    • INFORMATION_SCHEMA.QUERY_HISTORY:只能查询当前用户最近7天的查询记录,权限要求低。
    • SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY:可以查询整个账户最多1年的查询记录,但需要ACCOUNTADMIN角色或被授予该视图的访问权限。
  • 字段含义:
    • BYTES_SCANNED:查询扫描的总字节数。
    • TOTAL_ELAPSED_TIME:查询从提交到完成的总耗时,单位为毫秒。

内容的提问来源于stack exchange,提问作者Santhosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 04:15:30