【问题标题】:Replace value in deep nested schema Scala Spark Dataframe替换深层嵌套模式 Scala Spark Dataframe 中的值
【发布时间】:2019-07-07 22:18:36
【问题描述】:

我需要用null 替换数据框(带有嵌套模式)中的一些值,我见过这个solution 但它似乎只适用于一个 级别嵌套架构。

我的架构是这样的

root 
 ......
 ......
 ......
 |-- user: struct (nullable = true)
 |    |-- country: string (nullable = true)
 |    |-- id: string (nullable = true)
 |    |-- ip_address: string (nullable = true)
 |    |-- state: struct (nullable = true) 
 |    |    |-- level: long (nullable = true)
 |    |    |-- session_id: string (nullable = true) 
 |    |    |-- xp: long (nullable = true)

我想要做的是将user.state.leveluser.state.xp 替换为null,并保持我的数据框的其余部分保持不变。

有什么方法可以实现吗?

如果我关注this solution

val myUDF = udf((s:String) => {
    null
})

val structCols: Array[org.apache.spark.sql.Column] = badVersion.select($"user.*")
    .columns
    .map(name => col("user."+name))

val newDF = badVersion.withColumn(
    "user",
    struct((structCols:+myUDF($"user.country").as("country")):_*)
)

它适用于国家并替换价值,但如果我这样做

val newDF = badVersion.withColumn(
    "user",
    struct((structCols:+myUDF($"user.country").as("country"):+myUDF($"user.state.level").as("state.level")):_*)
)

只是将state.level 添加为新字段

【问题讨论】:

标签: scala apache-spark dataframe schema


【解决方案1】:

基于评论中的@Auprba 链接,我使用了this link 并提出了这个解决方案。

val replaced = df.selectExpr("""
    named_struct(
         .....................................................
         ....... Other columns ...............................
         ....... In a form of  ...............................
         ....... '{columnname}', {columnname}, ...............
         .....................................................
        'user', named_struct(
          'country', user.country,
          'id', user.id,
          'ip_address', user.ip_address,
          'state', named_struct('hard_currency', null, 'level', null, 'session_id', user.state.session_id, 'soft_currency', null, 'xp', null)
        )
    ) as named_struct
""").select("named_struct.*")
display(replaced)

【讨论】:

    猜你喜欢
    • 2020-04-01
    • 2018-10-29
    • 2020-12-02
    • 2019-09-26
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 2016-01-27
    相关资源
    最近更新 更多