gpt4 book ai didi

sql - 在R中并行化SQL查询

转载 作者:行者123 更新时间:2023-12-03 14:57:45 24 4
gpt4 key购买 nike

我有六个SQL查询,我通过R编写脚本,每个查询都花费很长时间(每个〜30分钟)。每个查询返回后,我便为一些标准报告处理数据。

我想做的是使用我的多核计算机从R并行运行这些SQL请求。

我在装有Oracle DB的Windows计算机上。我正在按照blog post使用doSNOW和foreach尝试拆分这些请求,这是我在stackoverflow上可以找到的最好的东西。

我已经能够使该过程适用于foreach的非并行%do%版本,但不适用于%dopar%。使用%dopar%,它仅返回一个空集。以下是设置表并运行查询的代码,因此您可以看到发生了什么。如果基本代码过多,请提前道歉。

我看过一些其他的R包,但没有找到明显的解决方案。另外,如果您有更好的方法来管理此类过程,我也很想听听它-请记住,我是一名分析师,而不是计算机科学家。谢谢!

#Creating a cluster
library(doSNOW)
cl <- makeCluster(c("localhost","localhost"), type = "SOCK")
registerDoSNOW(cl)

#Connecting to database through RODBC
ch=odbcConnect("",pwd = "xxxxx", believeNRows=FALSE)
#Test connection
odbcGetInfo(ch)

#Creating database tables for example purposes
qryA1 <- "create table temptable(test int)"
qryA2 <- "insert into temptable(test) values((1))"
qryA3 <- "select * from temptable"
qryA4 <- "drop table temptable"
qryB1 <- "create table temptable2(test int)"
qryB2 <- "insert into temptable2(test) values((2))"
qryB3 <- "select * from temptable2"
qryB4 <- "drop table temptable2"

sqlQuery(ch, qryA1)
sqlQuery(ch, qryA2)
doesItWork <- sqlQuery(ch, qryA3)
doesItWork
sqlQuery(ch, qryB1)
sqlQuery(ch, qryB2)
doesItWork <- sqlQuery(ch, qryB3)
doesItWork

result = c()
output = c()
databases <- list('temptable','temptable2')


#Non-parallel version of foreach
system.time(
foreach(i = 1:2)%do%{
result<-sqlQuery(ch,paste('SELECT * FROM ',databases[i]))
output[i] = result
}
)

output

#Parallel version of foreach

outputPar = c()

system.time(
foreach(i = 1:2)%dopar%{
#Connecting to database through RODBC
ch=odbcConnect(dsn ,pwd = "xxxxxx", believeNRows=FALSE)
#Test connection
odbcGetInfo(ch)
result<-sqlQuery(ch,paste('SELECT * FROM ',databases[i]))
outputPar[i] = result
}
)

outputPar

sqlQuery(ch, qryA4)
sqlQuery(ch, qryB4)

最佳答案

在串行foreach循环中进行赋值outputPar[i] = result时,这是可以的(但实际上不是foreach的预期用途)。当您在并行循环中进行此分配时,这是不正常的。参见http://tolstoy.newcastle.edu.au/R/e10/help/10/04/3237.html,获得Revolution的David Smith回答的类似问题。

作为解决方案,

system.time(
outputPar <- foreach(i = 1:2, .packages="RODBC")%dopar%{
#Connecting to database through RODBC
ch=odbcConnect(dsn ,pwd = "xxxxxx", believeNRows=FALSE)
#Test connection
odbcGetInfo(ch)
result<-sqlQuery(ch,paste('SELECT * FROM ',databases[i]))
result
}
)

关于sql - 在R中并行化SQL查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9931802/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com