我在Spark Scala(Spark版本:2.3和Spark-sql:2.11和Scala版本:2.11.0)中有四个数据帧,例如:
ratingsDf
+-------+---+
|ratings| id|
+-------+---+
| 0| 1|
| 1| 2|
| 1| 3|
| 0| 4|
| 0| 5|
| 1| 6|
| 1| 7|
| 1| 8|
| 0| 9|
| 1| 10|
+-------+---+
GpredictionsDf
+-----------+---+
|gprediction| id|
+-----------+---+
| 0| 1|
| 1| 2|
| 1| 3|
| 1| 4|
| 1| 5|
| 1| 6|
| 1| 7|
| 1| 8|
| 0| 9|
| 1| 10|
+-----------+---+
RpredictionsDf
+-----------+---+
|rprediction| id|
+-----------+---+
| 0| 1|
| 1| 2|
| 1| 3|
| 1| 4|
| 1| 5|
| 1| 6|
| 1| 7|
| 1| 8|
| 1| 9|
| 1| 10|
+-----------+---+
LpredictionsDf
+-----------+---+
|lprediction| id|
+-----------+---+
| 0| 1|
| 1| 2|
| 1| 3|
| 0| 4|
| 1| 5|
| 1| 6|
| 1| 7|
| 1| 8|
| 0| 9|
| 1| 10|
+-----------+---+
我需要通过联接“ id”列上的所有四个表来创建一个DataFrame。我尝试了以下两种方法执行此操作:
**方法1:**
val ensembleDf = GpredictionsDf.join(rpredjoin, gpredjoin("id") === RpredictionsDf("id"))
.join(LpredictionsDf, LpredictionsDf("id") === RpredictionsDf("id"))
.join(ratingsDf, ratingsDf("id") === RpredictionsDf("id"))
.select("gprediction", "rprediction", "lprediction", "ratings")
**方法2:**
ratingsDf.createOrReplaceTempView("ratingjoin");
GpredictionsDf.createOrReplaceTempView("gpredjoin")
RpredictionsDf.createOrReplaceTempView("rpredjoin")
LpredictionsDf.createOrReplaceTempView("lpredjoin")
val ensembleDf = sqlContext.sql("SELECT gprediction, rprediction, lprediction, ratings FROM gpredjoin, rpredjoin, lpredjoin, ratingjoin WHERE " +
"gpredjoin.id = rpredjoin.id AND rpredjoin.id = lpredjoin.id AND lpredjoin.id = ratingjoin.id");
但是,在两种情况下,我的联接均失败并返回空
ensembleDf.show();
+-----------+-----------+-----------+-------+
|gprediction|rprediction|lprediction|ratings|
+-----------+-----------+-----------+-------+
+-----------+-----------+-----------+-------+
知道为什么会这样吗?要解决此问题,我需要做什么代码更改?
答案 0 :(得分:0)
scala> val ratingsDf = Seq((0,1),(1,2),(1,3),(0,4),(0,5),(1,6),(1,7),(1,8),(0,9),(1,10)).toDF("ratings","id")
scala> val GpredictionsDf = Seq((0,1),(1,2),(1,3),(1,4),(1,5),(1,6),(1,7),(1,8),(0,9),(1,10)).toDF("gprediction", "id")
scala> val RpredictionsDf = Seq((0,1),(1,2),(1,3),(1,4),(1,5),(1,6),(1,7),(1,8),(1,9),(1,10)).toDF("rprediction", "id")
scala> val LpredictionsDf = Seq((0,1),(1,2),(1,3),(0,4),(1,5),(1,6),(1,7),(1,8),(0,9),(1,10)).toDF("lprediction", "id")
scala> val ensembleDf = GpredictionsDf.join(RpredictionsDf, GpredictionsDf("id") === RpredictionsDf("id") ).join(LpredictionsDf, LpredictionsDf("id") === RpredictionsDf("id")).join(ratingsDf, ratingsDf("id") === RpredictionsDf("id")).select("gprediction", "rprediction", "lprediction", "ratings")
scala> ensembleDf.show
+-----------+-----------+-----------+-------+
|gprediction|rprediction|lprediction|ratings|
+-----------+-----------+-----------+-------+
| 0| 0| 0| 0|
| 1| 1| 1| 1|
| 1| 1| 1| 1|
| 1| 1| 0| 0|
| 1| 1| 1| 0|
| 1| 1| 1| 1|
| 1| 1| 1| 1|
| 1| 1| 1| 1|
| 0| 1| 0| 0|
| 1| 1| 1| 1|
+-----------+-----------+-----------+-------+
这是我尝试过的,它给出了正确的值。我建议您检查用于加入的DF。