【问题标题】:dplyr / bigrquery way of querying/binding multiple tables of the same schema in BigQuery?dplyr / bigrquery 在 BigQuery 中查询/绑定相同架构的多个表的方式?
【发布时间】:2019-09-20 02:38:12
【问题描述】:

使用this自述文件中列出的方法,可以直接查询单个表,就像这样

library(bigrquery)
library(dplyr)

natality <- tbl(con, "natality")

natality %>%
  select(year, month, day, weight_pounds) %>% 
  head(10) %>%
  collect()

这使我们可以针对natality 编写常规的dplyr 代码,而bigrquery 会将dplyr 代码转换为BigQuery 查询。

但假设 natality 表是 2 个(或更多)单独的表,分别命名为 natality1natality2,并且它们可以rbind'd 在一起。

如何使用 BigQuery 执行此操作?也就是说,我怎样才能查询这些单独的表,就好像它们都在一起作为一个表一样?

我尝试了什么

我认为bind_rows 可能有效,但它没有。

library(bigrquery)
library(dplyr)

natality1 <- tbl(con, "natality1")
natality2 <- tbl(con, "natality2")

natality1 %>% bind_rows(., natality2) %>%
  select(year, month, day, weight_pounds) %>% 
  head(10) %>%
  collect()

注意事项

【问题讨论】:

    标签: r dplyr google-bigquery dbplyr


    【解决方案1】:

    我不知道dbplyr 具有rbind 功能。也许是因为不是每个数据库后端都支持它?

    我在 SQL Server 中解决此问题的方法是使用自定义函数编写显式 UNION ALL 查询(SQL Server 等效于 rbind)。下面是 SQL (link to other functions from this approach) 的示例函数。也许这个例子可以作为一个等效的bigquery 方法的灵感?

    union_all = function(table_a,table_b){
      # extract the connection
      db_connection = table_a$src$con
    
      sql_query = build_sql(con = db_connection,
                          sql_render(table_a), # the SQL code that defines table A
                          "\nUNION ALL\n", # insert union all command between them
                          sql_render(table_b) # the SQL code that defines table B
      )
    
      return(tbl(db_connection, sql(sql_query)))
    }
    

    这个想法是 union_all() 返回一个远程表对象,该对象由查询定义,其中包含 rbind 等效命令。

    【讨论】:

    • 事实证明我“做错了”。与其将单个表的多个部分移动到 BigQuery 中,我应该首先将它们组合起来(在存储中)——然后才将单个表移动到 BigQuery 中。非常感谢您的帮助(您的解决方案是一个非常有创意的解决方法)
    • 很高兴听到您找到了解决方案。也许您可以将其发布为正确答案?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 2017-07-07
    • 2017-05-19
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    相关资源
    最近更新 更多