]> code.communitydata.science - cdsc_reddit.git/blob - submissions_2_parquet_part2.py
1708548f18c12446e72d5d95964f4cc215bc0d64
[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 import pyspark
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
10 import os
11
12 spark = SparkSession.builder.getOrCreate()
13
14 sc = spark.sparkContext
15
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)
21
22 df = spark.read.parquet("/gscratch/comdata/output/reddit_submissions.parquet_temp")
23
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])
32
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')
36
37
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')
41
42 os.remove("/gscratch/comdata/output/reddit_submissions.parquet_temp")

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