]> code.communitydata.science - cdsc_reddit.git/blob - submissions_2_parquet_part2.py
Build comments dataset similarly to submissions and improve partitioning scheme
[cdsc_reddit.git] / submissions_2_parquet_part2.py
1 #!/usr/bin/env python3
2
3 # spark script to make sorted, and partitioned parquet files 
4
5 from pyspark.sql import functions as f
6 from pyspark.sql import SparkSession
7
8 spark = SparkSession.builder.getOrCreate()
9
10 sc = spark.sparkContext
11
12 conf = SparkConf().setAppName("Reddit submissions to parquet")
13 conf = conf.set("spark.sql.shuffle.partitions",2000)
14 conf = conf.set('spark.sql.crossJoin.enabled',"true")
15 conf = conf.set('spark.debug.maxToStringFields',200)
16 sqlContext = pyspark.SQLContext(sc)
17
18 df = spark.read.parquet("/gscratch/comdata/output/reddit_submissions.parquet_temp")
19
20 df = df.withColumn("subreddit_2", f.lower(f.col('subreddit')))
21 df = df.drop('subreddit')
22 df = df.withColumnRenamed('subreddit_2','subreddit')
23 df = df.withColumnRenamed("created_utc","CreatedAt")
24 df = df.withColumn("Month",f.month(f.col("CreatedAt")))
25 df = df.withColumn("Year",f.year(f.col("CreatedAt")))
26 df = df.withColumn("Day",f.dayofmonth(f.col("CreatedAt")))
27 df = df.withColumn("subreddit_hash",f.sha2(f.col("subreddit"), 256)[0:3])
28
29 # next we gotta resort it all.
30 df = df.repartition("subreddit")
31 df2 = df.sort(["subreddit","CreatedAt","id"],ascending=True)
32 df2 = df.sortWithinPartitions(["subreddit","CreatedAt","id"],ascending=True)
33 df2.write.parquet("/gscratch/comdata/output/reddit_submissions_by_subreddit.parquet", partitionBy=["Year",'Month'], mode='overwrite')
34
35
36 # # we also want to have parquet files sorted by author then reddit. 
37 df = df.repartition("author")
38 df3 = df.sort(["author","CreatedAt","id"],ascending=True)
39 df3 = df.sortWithinPartitions(["author","CreatedAt","id"],ascending=True)
40 df3.write.parquet("/gscratch/comdata/output/reddit_submissions_by_author.parquet", partitionBy=["Year",'Month'], mode='overwrite')
41
42 os.remove("/gscratch/comdata/output/reddit_submissions.parquet_temp")

Community Data Science Collective || Want to submit a patch?