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

如何通过AWS Glue将S3对象类型数据直接加载为Redshift Super类型?

解决AWS Glue将对象类型直接加载为Redshift Super类型的问题

你遇到的错误根源是Glue默认使用CSV作为向Redshift写入的中间格式,而CSV不支持struct这类复杂数据类型。要直接将对象类型映射为Redshift的SUPER类型,可以通过以下两种方案实现:

方案一:使用Spark Redshift连接器直接写入

放弃glueContext.write_dynamic_frame.from_jdbc_conf,改用from_options结合Spark Redshift连接器,指定JSON作为写入格式,让Redshift自动将struct解析为SUPER类型。

代码示例

# 将DynamicFrame转换为Spark DataFrame(获得更灵活的配置支持)
df = dynamic_frame.toDF()

# 配置Redshift连接与写入参数
redshift_config = {
    "url": "jdbc:redshift://your-cluster-endpoint:5439/your-database",
    "dbtable": "target_schema.target_table",
    "user": "redshift-user",
    "password": "redshift-password",
    "tempdir": "s3://your-temp-bucket/glue-temp/",
    "format": "json",
    "region": "your-aws-region",
    "aws_iam_role": "arn:aws:iam::your-account-id:role/redshift-access-role"
}

# 执行写入,struct类型会自动映射为Redshift SUPER类型
df.write \
  .format("com.databricks.spark.redshift") \
  .options(**redshift_config) \
  .mode("append")  # 根据需求选择append/overwrite等模式
  .save()

关键说明

  • tempdir指定Glue临时存放JSON文件的S3路径,需确保Redshift通过IAM角色拥有该路径的读写权限
  • 目标Redshift表的对应列必须提前定义为SUPER类型(例如CREATE TABLE target_table (id INT, complex_data SUPER);)
  • 该方式依赖Glue内置的Databricks Redshift连接器,无需额外安装依赖

方案二:先写JSON到S3,再执行Redshift COPY命令

如果需要更精细的控制,可以先将DynamicFrame导出为JSON文件到S3,再通过JDBC执行Redshift的COPY命令加载到SUPER列。

步骤1:将数据写入S3作为JSON文件

glueContext.write_dynamic_frame.from_options(
    frame=dynamic_frame,
    connection_type="s3",
    connection_options={"path": "s3://your-staging-bucket/redshift-staging/"},
    format="json"
)

步骤2:执行Redshift COPY命令

import psycopg2

# 建立Redshift连接
conn = psycopg2.connect(
    dbname="your-database",
    user="redshift-user",
    password="redshift-password",
    host="your-cluster-endpoint",
    port="5439"
)
cur = conn.cursor()

# 构造COPY命令,自动解析JSON到SUPER列
copy_sql = """
COPY target_schema.target_table (id, complex_data)
FROM 's3://your-staging-bucket/redshift-staging/'
IAM_ROLE 'arn:aws:iam::your-account-id:role/redshift-access-role'
FORMAT JSON 'auto';
"""

cur.execute(copy_sql)
conn.commit()

# 关闭资源
cur.close()
conn.close()

关键说明

  • FORMAT JSON 'auto'会让Redshift自动将JSON结构映射到SUPER类型
  • 若需要增量同步,可以在COPY命令中添加条件,或在Glue写入S3时按分区组织数据

内容的提问来源于stack exchange,提问作者이재열

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 17:25:19