如何根据字段的值对df进行模式推断?

dldeef67  于 2021-07-14  发布在  Spark
关注(0)|答案(1)|浏览(358)

我有一个领域 my_structure 这会根据 my_type ,例如

+--------------------+--------------------+
|             my_type|        my_structure|
+--------------------+--------------------+
|                   a|           [1, 2, 3]|
|                   a|           [4, 5, 6]|
|                   b|                null|
|                   c|               ['Z']|
|                   c|               ['X']|
``` `my_structure` 的结构会根据 `my_type` 的值:使用 `a` 是一个 `struct` 带3个元素,带 `b` 是 `null` 和 `c` 只有一个字符串值的结构。
如何拥有3个不同的Dataframe,每个Dataframe都有其特定的结构?
ecbunoof

ecbunoof1#

在这种情况下,方法 toJSON() 在基于感兴趣的值过滤df之后,推迟模式推断非常方便:

df.cache()

df.filter("my_type = 'a'").toJSON()
df_a = spark.read.json(df)

df.filter("my_type = 'b'").toJSON()
df_b = spark.read.json(df)

df.filter("my_type = 'c'").toJSON()
df_c = spark.read.json(df)

df.unpersist()

我是源头 df 因为在这种情况下它被调用了3次,所以要提高性能。
但就这样 df_a , df_b 以及 df_c 在“运行时”根据假设的值推断出3种不同的结构 my_type

相关问题