【问题标题】:Dbplyr: combine two tables and add the to the result to the database without loading them in memoryDbplyr:组合两个表并将结果添加到数据库中而不将它们加载到内存中
【发布时间】:2020-12-24 21:13:49
【问题描述】:

请查看帖子末尾的简单脚本。 我有一个包含两个表的数据库,我使用 union_all 将它们组合在一起。 有没有办法在不收集数据的情况下将结果添加到数据库中,即将它们加载到内存中? 非常感谢!




library(tidyverse)
library(DBI) # main DB interface
library(dbplyr) # dplyr back-end for DBs
#> 
#> Attaching package: 'dbplyr'
#> The following objects are masked from 'package:dplyr':
#> 
#>     ident, sql
library(RSQLite)


##create the databases

df1 <- tibble(x=1:20,y=rep(c("a", "b"), 10))


df2 <- tibble(x=101:120,y=rep(c("d", "e"), 10))




con <- dbConnect(drv=RSQLite::SQLite(), dbname="db.sqlite")

dbWriteTable(con,"mydata1",df1, overwrite=T)
dbWriteTable(con,"mydata2",df2, overwrite=T)

dbDisconnect(con) # closes our DB connection


con <- dbConnect(drv=RSQLite::SQLite(), dbname="db.sqlite")

mydb1 <- tbl(con, "mydata1")
mydb2 <- tbl(con, "mydata2")


mydb12 <- union_all(mydb1,mydb2)

#is there a way to add the union of mydb1 and mydb2 to the database without explicitly collecting the data?

reprex package (v0.3.0) 于 2020 年 12 月 24 日创建

【问题讨论】:

  • 只需在数据库中运行UNION ALL

标签: r dplyr dbplyr


【解决方案1】:

既然你在处理 SQL,那么就使用 SQL。

collect(mydb1) %>%
  nrow()
# [1] 20
DBI::dbExecute(con, "insert into mydata1 select * from mydata2")
# [1] 20
collect(mydb1) %>%
  nrow()
# [1] 40
collect(mydb1) %>%
  tail()
# # A tibble: 6 x 2
#       x y    
#   <int> <chr>
# 1   115 d    
# 2   116 e    
# 3   117 d    
# 4   118 e    
# 5   119 d    
# 6   120 e    

如果您想在新表中合并数据,那么这里有一个替代方案。

DBI::dbExecute(con, "
  create table mydata12 as
    select * from mydata2 union all select * from mydata1")

【讨论】:

  • 谢谢。关于您使用组合数据创建新表的建议(这是我真正追求的):是否需要将数据加载到内存中?我将使用大桌子,我绝对需要避免这种情况。我相信我应该是安全的,因为我们正在谈论的是 sql,但是你能确认一下吗?
  • 它不会将数据加载到 R 中;第一个dbExecute 命令返回给R 的唯一数据是20,一个整数,受该命令影响的行数;在第二个(创建)调用中,它再次返回一个整数(尽管不是返回的行数)。既不返回帧,也不将组合数据集加载到 R 中。
  • 我不禁想知道,你真的在​​处理 SQLite 中的“大表”吗?虽然我知道它可以处理大数据,但在某些情况下,您可能需要使用更多的集群 DBMS。
  • 好吧,如果数据是千兆字节的话。这些天不是大数据,有点适合.my.seasoned 工作站?
  • 谢谢!我希望有一个纯粹的 dbplyr 解决方案,但你的工作并提醒我是时候真正学习一些 sql 了。
猜你喜欢
  • 2020-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-22
  • 2023-02-16
  • 2011-03-14
相关资源
最近更新 更多