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

Spark Java API中的连接行数据集

  •  1
  • OOvic  · 技术社区  · 7 年前

    我想要两个连接两个数据集DS1和DS2以获得DS3

    DS1:

    +---------+--------------------+-----------+------------+
    |Compte   |         Lib        |ReportDebit|ReportCredit|
    +---------+--------------------+-----------+------------+
    |   447105|Autres impôts, ta...|    77171.0|         0.0|
    |   753000|Jetons de présenc...|     6839.0|         0.0|
    |   511107|Valeurs à l’encai...|        0.0|     77171.0|
    +---------+--------------------+-----------+------------+
    

    DS2:

    +---------+------------+
    |Compte   |SoldeBalance|
    +---------+------------+
    | 447105  |      992.13|
    | 111111  |     35065.0|
    

    我想得到这样的DS3:

    +---------+--------------------+-----------+------------+------------+
    |Compte   |           CompteLib|ReportDebit|ReportCredit|SoldeBalance|
    +---------+--------------------+-----------+------------+------------+
    |   447105|Autres impôts, ta...|    77171.0|         0.0|      992.13|
    |   753000|Jetons de présenc...|    6839.0 |         0.0|         0.0|
    |   511107|Valeurs à l’encai...|        0.0|     77171.0|         0.0|
        111111|                    |        0.0|         0.0|     35065.0|
    +---------+--------------------+-----------+------------+------------+
    

    有人能给我介绍一下Spark Java表达式的示例吗。 提前谢谢。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Mousa    7 年前

    可以通过应用完整的外部联接,然后用所需的值替换null值来实现这一点。

    import static org.apache.spark.sql.functions.*;
    
    ...
    
    ds1.join(ds2, ds1.col("Compte").equalTo(ds2.col("Compte")), "full_outer")
                    .select(ds1.col("Compte").alias("Compte1"),
                            ds2.col("Compte").alias("Compte2"),
                            ds1.col("Lib"),
                            ds1.col("ReportDebit"),
                            ds1.col("ReportCredit"),
                            ds2.col("SoldeBalance"))
                    .withColumn("Compte", when(col("Compte1").isNull(), col("Compte2")).otherwise(col("Compte1")))
                    .drop("Compte1", "Compte2")
                    .na().fill(0.0, new String[] { "ReportDebit", "ReportCredit", "SoldeBalance" })
                    .na().fill("", new String[] { "Lib" })
                    .show();
    

    输出:

    +--------------------+-----------+------------+------------+------+
    |                 Lib|ReportDebit|ReportCredit|SoldeBalance|Compte|
    +--------------------+-----------+------------+------------+------+
    |Valeurs à l’encai...|        0.0|     77171.0|         0.0|511107|
    |Autres impôts, ta...|    77171.0|         0.0|      992.13|447105|
    |                    |        0.0|         0.0|     35065.0|111111|
    |Jetons de présenc...|     6839.0|         0.0|         0.0|753000|
    +--------------------+-----------+------------+------------+------+