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

Spark Scala groupBy和merge

  •  -2
  • DeeeeRoy  · 技术社区  · 7 年前

    我们称之为数据帧 df :

    src tgt
    1   2
    1   3
    1   4
    2   1
    2   3
    2   5
    3   4
    4   2
    4   5
    4   6
    5   2
    

    我需要采取的数据和计数的数目传出边缘从src到 目标和从目标到src。如下所示。

    node    out_deg in-deg  total_deg
    1       3       1       4
    2       3       3       6
    3       1       2       3
    4       3       2       5
    5       1       2       3
    6       0       1       1
    

    总边数=in+out=3+2=5。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Tzach Zohar    7 年前

    你可以表演 fullouter 加入分组结果 src tgt

    df.groupBy("src").count().as("srcs")
      .join(df.groupBy("tgt").count().as("tgts"), $"src" === $"tgt", "fullouter")
      .select(
        coalesce($"src", $"tgt") as "node",
        coalesce($"srcs.count", lit(0)) as "out_deg",
        coalesce($"tgts.count", lit(0)) as "in_deg"
      ).withColumn("total_deg", $"in_deg" + $"out_deg")
      .orderBy($"node")
      .show()
    
    // +----+-------+------+---------+
    // |node|out_deg|in_deg|total_deg|
    // +----+-------+------+---------+
    // |   1|      3|     1|        4|
    // |   2|      3|     3|        6|
    // |   3|      1|     2|        3|
    // |   4|      3|     2|        5|
    // |   5|      1|     2|        3|
    // |   6|      0|     1|        1|
    // +----+-------+------+---------+
    

    但是:可能会有更有效的解决方案,我也建议您 Spark GraphX