【问题标题】:Spark - drop duplicates inside a json array field [duplicate]Spark - 在json数组字段中删除重复项[重复]
【发布时间】:2018-08-29 17:30:29
【问题描述】:

我分享我拥有的代码:

// define a case class
case class Zone(id: Int, team: String, members: Int ,name: String,  lastname: String)
        val df = Seq (
         (1,"team1", 3, "Jonh", "Doe"),
         (1,"team2", 4, "Jonh", "Doe"),
         (1,"team3", 5, "David", "Luis"),
         (2,"team4", 6, "Michael", "Larson"))
         .toDF("id", "team", "members", "name",  "lastname").as[Zone]

val df_grouped = df
   .withColumn("team_info", to_json(struct(col("team"), col("members"))))
   .withColumn("users", to_json(struct(col("name"), col("lastname"))))
   .groupBy("id")
   .agg(collect_list($"team_info").alias("team_info"), collect_list($"users").alias("users"))

df_grouped.show    
    +---+--------------------+--------------------+
    | id|           team_info|               users|
    +---+--------------------+--------------------+
    |  1|[{"team":"team1",...|[{"name":"Jonh","...|
    |  2|[{"team":"team4",...|[{"name":"Michael...|
    +---+--------------------+--------------------+

我需要删除“用户”列中的重复项,因为在我的情况下,如果数组中的 json 完全相同,则表示重复项。有没有办法用 df.withColumn 或任何其他方法改变该列的值?

【问题讨论】:

  • 提供您尝试过的代码
  • 对不起,我会添加代码。
  • 我已经想出了解决办法。使用 collect_set 而不是 collect_list

标签: json apache-spark dataframe duplicates to-json


【解决方案1】:

这可能不是最优雅的解决方案,但应该可以:

import org.apache.spark.sql.types._
import org.apache.spark.sql.Encoders

val df = sc.parallelize(
  Array("[{\"name\":\"John\",\"lastName\":\"Doe\"},{\"name\":\"John\",\"lastName\":\"Doe\"},{\"name\":\"David\",\"lastName\":\"Luis\"}]")
).toDF("users")

case class Users(name: String, lastName: String)
val schema = ArrayType(Encoders.product[Users].schema)

df.withColumn("u", from_json($"users", schema))
  .select("u")
  .as[Array[Users]]
  .map(_.distinct)
  .toDF("u")
  .withColumn("users", to_json($"u"))
  .select("users")

假设您的用户将拥有比您的示例更多的属性,只需将这些属性添加到案例类即可。只要类型简单,Encoder 就应该自动推断模式。

【讨论】:

    【解决方案2】:

    您可以使用 explodedropDuplicates 内置函数

    spark dropDuplicates based on json array field

    【讨论】:

      猜你喜欢
      • 2018-04-25
      • 2016-01-05
      • 1970-01-01
      • 2016-11-24
      • 2011-06-29
      • 2016-10-01
      • 2012-09-15
      • 2019-06-16
      相关资源
      最近更新 更多