【问题标题】:Error in Dataframe writing from R to Redshift从 R 到 Redshift 写入数据帧时出错
【发布时间】:2019-02-08 10:42:09
【问题描述】:

我在 R 中有一个具有各种不同数据类型的数据框。在将数据帧从 R 写入红移服务器时,我只收到字符和时间戳值的错误。我在下面添加 R 代码 sn-p 让您对这个问题有更多了解。

library(lubridate)
library(dplyr)

dat <- data.frame(id = letters[1:2], x = 2:3, date = now())
dat
str(dat)

drv <- dbDriver("PostgreSQL")
conn <- dbConnect(drv, host="redshift.amazonaws.com", port="5439", dbname="abcd", user="xyz", password="abc")

DBI::dbGetQuery(conn, "DROP TABLE test21;")
DBI::dbGetQuery(conn, "CREATE TABLE test21 ( id VARCHAR(255), x INT, date timestamp);")

chunksize = 100 

for (i in 1:ceiling(nrow(dat)/chunksize)) { 
query = paste0('INSERT INTO test21 (',paste0(colnames(dat),collapse = ','),') VALUES ')
  vals = NULL
  for (j in 1:chunksize) {
    k = (i-1)*chunksize+j
    if (k <= nrow(dat)) {
      vals[j] = paste0('(', paste0(dat[k,],collapse = ','), ')')
    }
  }
  query = paste0(query, paste0(vals,collapse=','))
  DBI::dbExecute(conn, query)
}

在运行最后一部分时,我收到以下错误:

  RS-DBI driver: (could not Retrieve the result : ERROR:  column "date" is of type timestamp without time zone but expression is of type numeric
HINT:  You will need to rewrite or cast the expression.

当我手动将值输入到红移表中时,结果如预期的那样。

DBI::dbGetQuery(conn, "INSERT INTO test21 (id, x, date) values ('a','2','2019-02-08 15:21:08'),('b','3','2019-02-08 15:21:08')")

我感觉到这个问题来自一些程序错误。在我对代码做错的地方请求您的建议。

【问题讨论】:

    标签: r postgresql dplyr amazon-redshift analytics


    【解决方案1】:

    在数据框的日期字段中,尝试替换

    now()

    substr(now(), 1, 19)

    【讨论】:

    • 通过使用 substr ,它将“数据”列的数据类型更改为字符。我也面临着变量“id”的这个问题,它本质上是字符。
    • 你能先把所有东西都转换成字符吗?
    • 试过那个。但是值正在变成红移。甚至列“id”在红移中也失去了意义。
    猜你喜欢
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2017-11-08
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多