代码之家  ›  专栏  ›  技术社区  ›  user3243499

如何在Scala中用唯一标识符分解Spark数据帧数组字段?

  •  0
  • user3243499  · 技术社区  · 7 年前

    +-----------+
    |        f1 |
    +-----------+
    |[a,b,c]    |
    |[e,f,g]    |
    |[h,i]      |
    +-----------+
    

    +-----------+--------+
    |        f1 |     uid|
    +-----------+--------+
    |a          |       1|
    |b          |       1|
    |c          |       1|
    |e          |       2|
    |f          |       2|
    |g          |       2|
    |h          |       3|
    |i          |       3|
    +-----------+--------+
    

    我可以执行爆炸直接在这里解释- Spark: Explode a dataframe array of structs and append id

    但我不知道如何添加 uid uid编号 uid编号

    1 回复  |  直到 7 年前
        1
  •  4
  •   user10398277    7 年前

    正确的方法是使用 monotonically_increasing_id

    val df = Seq(Seq("a", "b", "c"), Seq("e", "f", "g"), Seq("h", "i")).toDF("f1")
    
    df
      .withColumn("uid", monotonically_increasing_id)
      .withColumn("f1", explode($"f1"))
      .show
    // +---+---+                                                                       
    // | f1|uid|
    // +---+---+
    // |  a|  0|
    // |  b|  0|
    // |  c|  0|
    // |  e|  1|
    // |  f|  1|
    // |  g|  1|
    // |  h|  2|
    // |  i|  2|
    // +---+---+
    

    不要 使用 rank().over(Window.orderBy("f1")) . 它本质上是连续的,不可伸缩的,应该避免这种情况,本地的情况除外 Datasets (即返回 true isLocal