通过 R 将架构导入 BigQuery

Import schema into BigQuery via R

我有一个文件夹包含:

-- schema.yml
-- table1.csv
-- table2.csv
-- table4.csv

此文件夹存储在本地。

看了一会想问一下:

有没有办法直接从 R 将此架构批量上传到 BigQuery?

如果您想将 Rbigquery 一起使用。 Bigquery documentation recommends to use tibble in conjuntion with bigrquery.

bigrquery

这个包实现了包中的bigquery rest API, where you can make use of low_level_api来执行bigquery操作。

对于您的具体情况,您可以 read your schema.yml file and use it to create the table fields data and create the bq_fields needed to create your table trough bq_table。在最后一点,您可以读取文件并创建单个文件或迭代来填充您的 table。这将取决于您的标准和您处理的数据量。

这是一个开始在笔记本中使用带有 bigrquery 的 tibble 的小示例。 (我使用 GCP 的 R python 笔记本)

library(tibble)
library(bigrquery)

# authenticate
# use if notebook is outside gcp
#bigrquery::bq_auth(path = '/Users/me/restofthepath/bigquery-credentials.json')

# set my project ID and dataset name
project_id <- '<my-project-id>'
dataset_name <- '<my-dataset-name>'

# set fields
sample_fields<-list(
  bq_field(name = "name", type = "string"),
  bq_field("age", "integer")
)

# set values
sample_df<-tribble(
   ~name,  ~age,
   "erika",  21,
   "isabel", 18, 
)

# create table and upload your values
sample_table = bq_table(project = project_id, dataset = dataset_name, table = '<my-table-name>')
bq_table_create(x = sample_table, fields = as_bq_fields(sample_fields))
bq_table_upload(x = sample_table, values = sample_df, create_disposition='CREATE_IF_NEEDED', write_disposition='WRITE_APPEND')

注意:您可能需要实施环境并安装库。为此你可以这样做:

# install libraries
install.packages("bigrquery")
install.packages("tibble")

# set env
print(Sys.setenv(BIGQUERY_TEST_PROJECT = "<my-project-id>"))  
Sys.getenv("BIGQUERY_TEST_PROJECT")