scala 如何将VARIANT类型从Snowflake转换为Spark上的struct数组?

4bbkushb  于 8个月前  发布在  Scala
关注(0)|答案(2)|浏览(79)

我在下面的 snowflake 上有一张table。myarray列是VARIANT类型的json格式:

我使用Snowflake Spark连接器在Spark上检索该表:

val mydf: DataFrame = spark.read
.format("snowflake")
.options(options)
.option("query", "SELECT uid, myarray FROM mytable")
.load()

问题是myarray是字符串。不方便的数据类型为我的目的。
我想得到的点,我可以检索索引和值作为结构类型:

df.select("uid", "myarray.index", "myarray.value")

你知道什么是最好的方法来应用一个模式到myarray列,而不失去它对其他列的位置(uid)?

thtygnil

thtygnil1#

在我的例子中,我写了一个int类型数组的列,snowflake连接器然后将在Snowflake中创建一个变量类型列的表。
然后,当我读这张有 snowflake 的表格时,我得到了完全相同的问题。Snowflake变体类型Map为String。
我已经找到了一个解决方案,通过使用Sparks from_json函数Map框架。显然,变量类型列中的数据默认为json。
以下代码适用于我:

spark.read
      .format(SNOWFLAKE_SOURCE_NAME)
      .options(sfOptions)
      .option("dbtable", tableName2)
      //.schema(schema1) // original schema doens't match
      .load()
      .withColumn("NUM", $"NUM".cast(IntegerType))
      .withColumn("ARR", from_json($"ARR", ArrayType(IntegerType)))
      .withColumn("MAP", from_json($"MAP", MapType(StringType, IntegerType)))
      .withColumn("OBJ", from_json($"OBJ", StructType(Array(StructField("STR", StringType, nullable = false)))))
lnvxswe2

lnvxswe22#

有没有办法不传递列名

.withColumn("NUM", $"NUM".cast(IntegerType))
      .withColumn("ARR", from_json($"ARR", ArrayType(IntegerType)))
      .withColumn("MAP", from_json($"MAP", MapType(StringType, IntegerType)))
      .withColumn("OBJ", from_json($"OBJ", StructType(Array(StructField("STR", StringType, nullable = false)))))

相关问题