识别 Ruby 中的 Redshift COPY 失败记录

Identify Redshift COPY failing records in Ruby

执行COPY命令时,会打印一些信息,例如:

INFO:  Load into table '<table>' completed, 22666 record(s) loaded successfully.
INFO:  Load into table '<table>' completed, 1 record(s) could not be loaded.  Check 'stl_load_errors' system table for details.

我需要识别失败的记录。

因此我需要两件事:

一种方法是访问 table stl_load_errors 中可见的 query 标识符,但我不知道如何通过代码访问它。

(我目前使用pg gem连接到redshift)

stl_load_errors 是 Redshift 中的一个 table,它(正如您可能已经猜到的那样)包括加载到 Redshift 时发生的所有错误。因此,您可以通过执行以下操作来查询它:

SELECT * FROM stl_load_errors

现在,使用以下代码段回答您的问题:

database = PG.connect(redshift)
begin
  query = "COPY %s (%s) FROM 's3://%s/%s' CREDENTIALS 'aws_access_key_id=%s;aws_secret_access_key=%s' CSV GZIP" %
[ table, columns, s3_bucket, s3_key, access_key_id, secret_access_key ]

  database.exec(query)
  puts 'File succesfully imported'
rescue PG::InternalError
  res = database.exec("SELECT line_number, colname, err_reason FROM pg_catalog.stl_load_errors WHERE filename = 's3://#{s3_bucket}/#{s3_key}'")
  res.each do |row|
    puts "Importing failed:\n> Line %s\n> Column: %s\n> Reason: %s" % row.values_at('line_number', 'colname', 'err_reason')
 end
end

那应该输出你需要的所有信息,回忆像redshifttablecolumnss3_buckets3_key、[=19这样的变量=],并且 secret_access_key 取决于您的配置。

更新:

要回答您在下面的评论,更具体地说,您可以使用这样的查询:

"SELECT lines_scanned FROM pg_catalog.stl_load_commits WHERE filename = 's3://#{s3_bucket}/#{s3_key}' AND errors = -1"