sql - 如何使用 SparkR 在 Spark SQL 中传递变量?
问题描述
我是 SparkR 的新手。我正在尝试使用 Qubole Notebook 使用 SparkR 在数据集上编写查询。采取了几个过程但没有得到输出。
数据:表_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 中传递变量?
解决方案
过滤可以使用函数中的子句where
或sql
直接使用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
. 从名为 的 SparkDataFrame 创建临时视图sdf
。然后就可以用它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 2020
推荐阅读
- mysql - 添加 json 列时遇到 Knex.js & MySql 错误
- reactjs - 三元运算符没有按预期工作
- c - 带压缩的加权快速联合不比没有压缩快
- mysql - 如何将sql查询结果拆分成新的增量表
- php - 如何在 $.post({}) ajax 中使用内容类型
- css - 在不使用 Vuetify 的断点服务的情况下应用不同的 CSS 类
- c# - C# 类库项目 (RAGE:MP) 中缺少 SQL DLL
- java - 使用 RemoteWebDriver 和 Selenium 时启用浏览器日志不起作用
- typescript - 使用相同类型名称时如何精确识别TS错误消息中的类型
- javascript - HTML / JS - 如何放大表格并拖动它?