Spark (Scala) 在 for 循环内执行数据帧 [英] Spark (Scala) execute dataframe within for loop
本文介绍了Spark (Scala) 在 for 循环内执行数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用的是 spark 1.6.1 版本.我需要在循环中执行数据帧.
I am using spark 1.6.1 version. I have requirement to execute dataframe in loop.
for ( i <- List ('a','b')){
val i = sqlContext.sql("SELECT i, col1, col2 FROM DF1")}
我希望这个数据帧被执行两次(i = a
和 i = b
).
I want this dataframe to be executed twice (i = a
and i = b
).
推荐答案
您的代码几乎是正确的.除了两件事:
Your code is almost correct. Except two things :
i
已经在你的for
循环中使用,所以不要在val i =
中使用它- 如果要在字符串中使用
i
的值,请使用字符串插值
i
is already used in yourfor
loop so don't use it inval i =
- If you want to use the value of
i
in a string, use String Interpolation
所以你的代码应该是这样的:
So your code should look like :
for (i <- List ('a','b')) {
val df = sqlContext.sql(s"SELECT $i, col1, col2 FROM DF1")
df.show()
}
<小时>
在作者评论后
你可以用一个 .map
然后一个 .reduceLeft
来做到这一点:
You can do this with a .map
and then a .reduceLeft
:
// All your dataframes
val dfs = Seq('a','b').map { i =>
sqlContext.sql(s"SELECT $i, col1, col2 FROM DF1")
}
// Then you can reduce your dataframes into one
val unionDF = dfs.reduceLeft((dfa, dfb) =>
dfa.unionAll(dfb)
)
这篇关于Spark (Scala) 在 for 循环内执行数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文