首页 > 解决方案 > Bigrquery 强制将字符串强制转换为整数(模式是字符串)

问题描述

我正在使用邮政编码,其中当然有前导零。我正确加载了我的数据框以保留 R 中的前导零,但上传步骤似乎失败了。这就是我的意思:

这是我的 minimum.csv 文件:

zip,val
07030,10
10001,100
90210,1000
60602,10000

这是R代码

require("bigrquery")
filename <- "minimal.csv"
tablename <- "as_STRING"
ds <- bq_dataset(project='myproject', dataset="zips")

我也正确地在我的模式中设置类型以期望它们作为字符串。

# first pass
df <- read.csv(filename, stringsAsFactors=F)
# > df
#     zip   val
# 1  7030    10
# 2 10001   100
# 3 90210  1000
# 4 60602 10000

# uh oh!  Let's fix it!

cols <- unlist(lapply(df, class))
cols[[1]] <- "character" # make zipcode a character

# then reload
df2 <- read.csv(filename, stringsAsFactors=F, colClasses=cols)
# > df2
#     zip   val
# 1 07030    10
# 2 10001   100
# 3 90210  1000
# 4 60602 10000

# much better!  You can see my zips are now strings.

但是,当我尝试上传字符串时,bigrquery 界面抱怨我正在上传整数,但事实并非如此。这是架构,需要字符串:

# create schema
bq_table_create(bq_table(ds, tablename), fields=df2) # using df2, which has strings

# now prove it got the strings right:
    > bq_table_meta(bq_table(ds, tablename))$schema$fields
    [[1]]
    [[1]]$name
    [1] "zip"

    [[1]]$type
    [1] "STRING"                # GOOD, ZIP IS A STRING!

    [[1]]$mode
    [1] "NULLABLE"


    [[2]]
    [[2]]$name
    [1] "val"

    [[2]]$type
    [1] "INTEGER"

    [[2]]$mode
    [1] "NULLABLE"

现在是时候上传了......

bq_table_upload(bq_table(ds, tablename), df2) # using df2, with STRINGS
Error: Invalid schema update. Field zip has changed type from STRING to INTEGER [invalid]

嗯?这个无效的架构更新是什么,我怎样才能阻止它尝试将我的字符串(数据包含和架构是)更改为整数,我的数据不包含,架构不包含?

是否正在发生 javascript 序列化并将我的字符串转回整数?

标签: rgoogle-bigquerybigrquery

解决方案


这是因为 BigQuery 会在未指定架构时自动检测架构。这可以通过指定fields参数来解决,如下所示(有关更多详细信息,请参阅此类似问题):

bq_table_upload(bq_table(ds, tablename), df2,fields = list(bq_field("zip", "string"),bq_field("val", "integer")))

更新:

查看代码,bq_table_upload正在调用bq_perform_upload,它将参数fields作为模式。最后,它解析data frameasJSON文件以将其上传到 BigQuery。


推荐阅读