glue_job.pyAWS Glue · PySpark
# Glue 5.0 · Spark 3.5.4 · Python 3.11
import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from awsglue.context import GlueContext
from awsglue.job import Job
from awsglue.dynamicframe import DynamicFrame
from pyspark.sql import functions as F
from pyspark.context import SparkContext
args = getResolvedOptions(sys.argv, ["JOB_NAME"])
sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args["JOB_NAME"], args) # loads the bookmark state
# 1. Source: JSON files under the S3 landing prefix
src = glueContext.create_dynamic_frame.from_options(
connection_type="s3",
connection_options={"paths": ["s3://lake/raw/orders/"], "recurse": True},
format="json",
transformation_ctx="src_orders", # bookmark key
)
# 2. amount arrives as choice<int,string> — make it a double
resolved = ResolveChoice.apply(
frame=src,
specs=[("amount", "cast:double")],
transformation_ctx="resolved",
)
# 3. Rename + cast (unmapped fields are dropped)
mapped = ApplyMapping.apply(
frame=resolved,
mappings=[
("id", "string", "order_id", "string"),
("cust_id", "string", "customer_id", "string"),
("ts", "string", "order_ts", "timestamp"),
("amount", "double", "amount", "double"),
("status", "string", "status", "string"),
],
transformation_ctx="mapped",
)
# 4. Drop test orders
kept = Filter.apply(
frame=mapped,
f=lambda r: r["status"] != "test",
transformation_ctx="no_test",
)
# 5. Derive the partition columns from the order time
ts = F.col("order_ts")
df = (
kept.toDF()
.withColumn("year", F.date_format(ts, "yyyy"))
.withColumn("month", F.date_format(ts, "MM"))
)
out = DynamicFrame.fromDF(df, glueContext, "out")
# 6. Sink: Parquet on S3 (appends new files)
glueContext.write_dynamic_frame.from_options(
frame=out,
connection_type="s3",
connection_options={
"path": "s3://lake/curated/orders/",
"partitionKeys": ["year", "month"],
},
format="parquet",
transformation_ctx="sink_orders",
)
job.commit() # saves the bookmark state atomically
job parameters · aws glue create-job / start-job-runbash
# Create the job (DefaultArguments = job parameters)
aws glue create-job \
--name orders-incremental \
--role AWSGlueServiceRole-lake \
--glue-version 5.0 \
--command Name=glueetl,PythonVersion=3,ScriptLocation=s3://lake/jobs/glue_job.py \
--worker-type G.2X --number-of-workers 30 \
--execution-class STANDARD \
--default-arguments '{
"--job-bookmark-option": "job-bookmark-disable",
"--TempDir": "s3://lake/tmp/glue/"
}'
# Run it (run arguments override the defaults for one run)
aws glue start-job-run --job-name orders-incremental
# Reprocess everything from scratch
aws glue reset-job-bookmark --job-name orders-incremental