将数据从胶水加载到雪花

时间:2020-06-11 19:22:29

标签: mongodb pyspark apache-spark-sql snowflake-cloud-data-platform aws-glue

我正在尝试在胶水上运行ETL作业,在此我将数据从mongodb提取到spark数据帧中并粘贴到胶水中,然后将其加载到雪花中。

这是Spark数据框的示例架构

|-- login: struct (nullable = true)
 |    |-- login_attempts: integer (nullable = true)
 |    |-- last_attempt: timestamp (nullable = true)
 |-- name: string (nullable = true)
 |-- notifications: struct (nullable = true)
 |    |-- bot_review_queue: boolean (nullable = true)
 |    |-- bot_review_queue_web_push: boolean (nullable = true)
 |    |-- bot_review_queue_web_push_admin: boolean (nullable = true)
 |    |-- weekly_account_summary: struct (nullable = true)
 |    |    |-- enabled: boolean (nullable = true)
 |    |-- weekly_summary: struct (nullable = true)
 |    |    |-- enabled: boolean (nullable = true)
 |    |    |-- day: integer (nullable = true)
 |    |    |-- hour: integer (nullable = true)
 |    |    |-- minute: integer (nullable = true)
 |-- query: struct (nullable = true)
 |    |-- email_address: string (nullable = true)

我正在尝试将数据按原样加载到雪花中,并将结构列作为雪花中的json有效负载加载,但是会引发以下错误

An error occurred while calling o81.collectToPython.com.mongodb.spark.exceptions.MongoTypeConversionException:Cannot cast ARRAY into a StructType

我还尝试将struct列转换为字符串并加载它,但它或多或少会引发相同的错误

An error occurred while calling o106.save.  com.mongodb.spark.exceptions.MongoTypeConversionException: Cannot cast STRING into a StructType

如果能获得帮助,请多谢。

下面用于投射和加载的代码。

dynamic_frame = glueContext.create_dynamic_frame.from_options(connection_type="mongodb",
                                                  connection_options=read_mongo_options)
user_df_cast = user_df.select(user_df.login.cast(StringType()),'name',user_df.notifications.cast(StringType()))
datasinkusers = user_df_cast.write.format(SNOWFLAKE_SOURCE_NAME).options(**sfOptions).option("dbtable", "users").mode("append").save()

1 个答案:

答案 0 :(得分:1)

如果您在Snowflake中的users表具有以下架构,则不需要广播,因为StructType fields of a SparkSQL DataFrame将自动映射到VARIANT type in Snowflake

CREATE TABLE users (
    login VARIANT
   ,name STRING
   ,notifications VARIANT
   ,query VARIANT
)

只需执行以下操作,无需任何转换,因为Snowflake Spark Connector understands the data-type会自行转换为适当的JSON表示形式:

user_df = glueContext.create_dynamic_frame.from_options(
  connection_type="mongodb",
  connection_options=read_mongo_options
)

user_df
  .toDF()
  .write
  .format(SNOWFLAKE_SOURCE_NAME)
  .options(**sfOptions)
  .option("dbtable", "users")
  .mode("append")
  .save()

如果您绝对需要将StructType字段存储为纯JSON字符串,则需要使用to_json SparkSQL function显式转换它们:

from pyspark.sql.functions import to_json

user_df_cast = user_df.select(
  to_json(user_df.login),
  user_df.name,
  to_json(user_df.notifications)
)

这会将JSON字符串存储为简单的VARCHAR类型,这样就不会在没有semi-structured data storage and querying capabilities步骤(效率低下)的情况下直接利用Snowflake的PARSE_JSON

考虑使用上面显示的VARIANT方法,这将允许您直接在字段上执行查询:

SELECT
    login:login_attempts
   ,login:last_attempt
   ,name
   ,notifications:weekly_summary.enabled
FROM users