3 # spark script to make sorted, and partitioned parquet files
6 from pyspark.sql import functions as f
7 from pyspark.sql.types import *
8 from pyspark import SparkConf, SparkContext
9 from pyspark.sql import SparkSession, SQLContext
12 spark = SparkSession.builder.getOrCreate()
14 sc = spark.sparkContext
16 conf = SparkConf().setAppName("Reddit submissions to parquet")
17 conf = conf.set("spark.sql.shuffle.partitions",2000)
18 conf = conf.set('spark.sql.crossJoin.enabled',"true")
19 conf = conf.set('spark.debug.maxToStringFields',200)
20 sqlContext = pyspark.SQLContext(sc)
22 df = spark.read.parquet("/gscratch/comdata/output/reddit_submissions.parquet_temp")
24 df = df.withColumn("subreddit_2", f.lower(f.col('subreddit')))
25 df = df.drop('subreddit')
26 df = df.withColumnRenamed('subreddit_2','subreddit')
27 df = df.withColumnRenamed("created_utc","CreatedAt")
28 df = df.withColumn("Month",f.month(f.col("CreatedAt")))
29 df = df.withColumn("Year",f.year(f.col("CreatedAt")))
30 df = df.withColumn("Day",f.dayofmonth(f.col("CreatedAt")))
31 df = df.withColumn("subreddit_hash",f.sha2(f.col("subreddit"), 256)[0:3])
33 # next we gotta resort it all.
34 df2 = df.sort(["subreddit","author","id","Year","Month","Day"],ascending=True)
35 df2.write.parquet("/gscratch/comdata/output/reddit_submissions_by_subreddit.parquet", partitionBy=["Year",'Month'], mode='overwrite')
38 # # we also want to have parquet files sorted by author then reddit.
39 df3 = df.sort(["author","CreatedAt","subreddit","id","Year","Month","Day"],ascending=True)
40 df3.write.parquet("/gscratch/comdata/output/reddit_submissions_by_author.parquet", partitionBy=["Year",'Month'], mode='overwrite')
42 os.remove("/gscratch/comdata/output/reddit_submissions.parquet_temp")