Adding timestamp column in importing data in redshift using AWS Glue Job

感情迁移 提交于 2019-12-04 18:39:18

Convert DynamicFrame to spark's DataFrame, add a new column with current timestamp and then convert it back to DynamicFrame before writing.

import org.apache.spark.sql.functions._

...

val timestampedDf = dropnullfields3.toDF().withColumn("TimeStamp", current_timestamp())
val timestamped4 = DynamicFrame(timestampedDf, glueContext)

Here how your Python code should look like:

import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext, DynamicFrame
from awsglue.job import Job
from pyspark.sql.functions import current_timestamp

## @params: [TempDir, JOB_NAME]
args = getResolvedOptions(sys.argv, ['TempDir','JOB_NAME'])

sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args['JOB_NAME'], args)

datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "sampledb", table_name = "abs", transformation_ctx = "datasource0")
applymapping1 = ApplyMapping.apply(frame = datasource0, mappings = [("ColumnA", "char", "ColumnA", "char"), ("ColumnB", "char", "ColumnB", "char")], transformation_ctx = "applymapping1")
resolvechoice2 = ResolveChoice.apply(frame = applymapping1, choice = "make_cols", transformation_ctx = "resolvechoice2")
dropnullfields3 = DropNullFields.apply(frame = resolvechoice2, transformation_ctx = "dropnullfields3")
# add TimeStamp column
timestampedDf = dropnullfields3.toDF().withColumn("TimeStamp", current_timestamp())
timestamped4 = DynamicFrame.fromDF(timestampedDf, glueContext, "timestampedDf")
datasink4 = glueContext.write_dynamic_frame.from_jdbc_conf(frame = timestamped4, catalog_connection = "TESTDB", connection_options = {"dbtable": "TABLEA", "database": "anasightprd01"}, redshift_tmp_dir = args["TempDir"], transformation_ctx = "datasink4")

Although there's likely a way to obtain the current date time in your glue code, another common way to timestamp data on insertion is to add a TIMESTAMP data column to your Redshift table, which is bound to a default of GETDATE()

CREATE TABLE myschema.mytable
(
    ... OTHER Fields here
    insertedtimestamp TIMESTAMP WITH TIME ZONE DEFAULT(GETDATE())
);

The trick with inserting is to ensure that insertedtimestamp column is not specified in the INSERT INTO or COPY fields - as rows are added to the table

INSERT INTO myschema.mytable(Col1, Col2 ...) -- NB no `insertedtimestamp` column
VALUES ('col1', 'col2' ...);

-- Value of insertedtimestamp will be auto time stamped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!