我是SparkR的新手。我正在尝试使用Qubole Notebook使用SparkR在数据集上编写查询。执行了几个过程,但没有得到输出。
数据: Table_A
ID Name month year
1 A 2 2020
2 B 2 2019
3 c 12 2019所需输出:
ID Name month year
1 A 2 2020

变量:
month_value= 2
year_value = 2020流程1:
temp_data = sql("
select *
from Table_A
where month = $month_value and year = $year_value")流程2:
temp_data = sql(s"
select *
from Table_A
where month = $month_value and year = $year_value")流程3:
temp_data = sql("
select *
from Table_A
where month = {0} and year = {1}".format(month_value,year_value))流程4:
temp_data = sql("
select *
from Table_A
where month = ${month_value} and year = ${year_value}")如何使用SparkR传递spark SQL中的变量?
发布于 2020-04-05 07:37:16
过滤可以使用sql函数中的where子句或直接使用filter函数来完成。
使用示例数据进行设置:
library(SparkR, lib.loc = c(file.path(Sys.getenv("SPARK_HOME"), "R", "lib")))
sparkR.session(master = "local[*]", sparkConfig = list(spark.driver.memory = "8g"))
local_df <- data.frame(ID=c(1, 2 ,3),
Name=c("A", "B", "c"),
month=c(2, 2, 12),
year=c(2020, 2019, 2019))
month_value <- 2
year_value <- 2020
sdf <- createDataFrame(local_df)第一种方法是使用sql。从名为sdf的SparkDataFrame创建临时视图。然后,您可以使用glue来编写sql代码。它是一个字符串插值器,比使用paste更简洁。
# 1) SQL function (string interpolation)
createOrReplaceTempView(sdf, "Table_A")
(sql_expanded <- as.character(glue::glue(
"select * from Table_A where (month == {month_value}) and (year == {year_value})")))
head(sql(sql_expanded))结果是:
> (sql_expanded <- glue::glue(
+ "select * from Table_A where (month == {month_value}) and (year == {year_value})"))
select * from Table_A where (month == 2) and (year == 2020)
> head(sql(as.character(sql_expanded)))
ID Name month year
1 1 A 2 2020第二种选择,使用filter
> head(filter(sdf, sdf$month == month_value & sdf$year == year_value))
ID Name month year
1 1 A 2 2020https://stackoverflow.com/questions/60862315
复制相似问题