4 # 1. from gz to arrow parquet
5 # 2. from arrow parquet to spark parquet
7 from collections import defaultdict
12 from datetime import datetime
13 from subprocess import Popen, PIPE
14 from multiprocessing import Pool, SimpleQueue
16 dumpdir = "/gscratch/comdata/raw_data/reddit_dumps/submissions"
18 def find_json_files(dumpdir):
19 base_pattern = "RS_20*.*"
21 files = glob.glob(path.join(dumpdir,base_pattern))
23 # build a dictionary of possible extensions for each dump
24 dumpext = defaultdict(list)
26 fname, ext = path.splitext(fpath)
27 dumpext[fname].append(ext)
29 ext_priority = ['.zst','.xz','.bz2']
31 for base, exts in dumpext.items():
37 for ext in ext_priority:
43 files = list(find_json_files(dumpdir))
46 lines = open_input_file(fh)
50 def open_fileset(files):
53 lines = open_input_file(fh)
57 def open_input_file(input_filename):
58 if re.match(r'.*\.7z$', input_filename):
59 cmd = ["7za", "x", "-so", input_filename, '*']
60 elif re.match(r'.*\.gz$', input_filename):
61 cmd = ["zcat", input_filename]
62 elif re.match(r'.*\.bz2$', input_filename):
63 cmd = ["bzcat", "-dk", input_filename]
64 elif re.match(r'.*\.bz', input_filename):
65 cmd = ["bzcat", "-dk", input_filename]
66 elif re.match(r'.*\.xz', input_filename):
67 cmd = ["xzcat",'-dk', '-T 20',input_filename]
68 elif re.match(r'.*\.zst',input_filename):
69 cmd = ['zstd','-dck', input_filename]
71 input_file = Popen(cmd, stdout=PIPE).stdout
72 except NameError as e:
74 input_file = open(input_filename, 'r')
78 def parse_submission(post, names = None):
80 names = ['id','author','subreddit','title','created_utc','permalink','url','domain','score','ups','downs','over_18','has_media','selftext','retrieved_on','num_comments','gilded','edited','time_edited','subreddit_type','subreddit_id','subreddit_subscribers','name','is_self','stickied','is_submitter','quarantine','error']
83 post = json.loads(post)
84 except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e:
87 row = [None for _ in names]
88 row[-1] = "json.decoder.JSONDecodeError|{0}|{1}".format(e,post)
94 if name == 'created_utc' or name == 'retrieved_on':
95 val = post.get(name,None)
97 row.append(datetime.fromtimestamp(int(post[name]),tz=None))
100 elif name == 'edited':
102 if type(val) == bool:
107 row.append(datetime.fromtimestamp(int(val),tz=None))
108 elif name == "time_edited":
110 elif name == 'has_media':
111 row.append(post.get('media',None) is not None)
113 elif name not in post:
116 row.append(post[name])
121 stream = open_fileset(files)
125 rows = pool.imap_unordered(parse_submission, stream, chunksize=int(N/28))
127 from itertools import islice
130 import pyarrow.parquet as pq
133 pa.field('id', pa.string(),nullable=True),
134 pa.field('author', pa.string(),nullable=True),
135 pa.field('subreddit', pa.string(),nullable=True),
136 pa.field('title', pa.string(),nullable=True),
137 pa.field('created_utc', pa.timestamp('ms'),nullable=True),
138 pa.field('permalink', pa.string(),nullable=True),
139 pa.field('url', pa.string(),nullable=True),
140 pa.field('domain', pa.string(),nullable=True),
141 pa.field('score', pa.int64(),nullable=True),
142 pa.field('ups', pa.int64(),nullable=True),
143 pa.field('downs', pa.int64(),nullable=True),
144 pa.field('over_18', pa.bool_(),nullable=True),
145 pa.field('has_media',pa.bool_(),nullable=True),
146 pa.field('selftext',pa.string(),nullable=True),
147 pa.field('retrieved_on', pa.timestamp('ms'),nullable=True),
148 pa.field('num_comments', pa.int64(),nullable=True),
149 pa.field('gilded',pa.int64(),nullable=True),
150 pa.field('edited',pa.bool_(),nullable=True),
151 pa.field('time_edited',pa.timestamp('ms'),nullable=True),
152 pa.field('subreddit_type',pa.string(),nullable=True),
153 pa.field('subreddit_id',pa.string(),nullable=True),
154 pa.field('subreddit_subscribers',pa.int64(),nullable=True),
155 pa.field('name',pa.string(),nullable=True),
156 pa.field('is_self',pa.bool_(),nullable=True),
157 pa.field('stickied',pa.bool_(),nullable=True),
158 pa.field('is_submitter',pa.bool_(),nullable=True),
159 pa.field('quarantine',pa.bool_(),nullable=True),
160 pa.field('error',pa.string(),nullable=True)])
162 with pq.ParquetWriter("/gscratch/comdata/output/reddit_submissions.parquet_temp",schema=schema,compression='snappy',flavor='spark') as writer:
164 chunk = islice(rows,N)
165 pddf = pd.DataFrame(chunk, columns=schema.names)
166 table = pa.Table.from_pandas(pddf,schema=schema)
167 if table.shape[0] == 0:
169 writer.write_table(table)
174 from pyspark.sql import functions as f
175 from pyspark.sql.types import *
176 from pyspark import SparkConf, SparkContext
177 from pyspark.sql import SparkSession, SQLContext
179 spark = SparkSession.builder.getOrCreate()
180 sc = spark.sparkContext
182 conf = SparkConf().setAppName("Reddit submissions to parquet")
183 conf = conf.set('spark.sql.crossJoin.enabled',"true")
185 sqlContext = pyspark.SQLContext(sc)
187 df = spark.read.parquet("/gscratch/comdata/output/reddit_submissions.parquet_temp")
189 df = df.withColumn("subreddit_2", f.lower(f.col('subreddit')))
190 df = df.drop('subreddit')
191 df = df.withColumnRenamed('subreddit_2','subreddit')
192 df = df.withColumnRenamed("created_utc","CreatedAt")
193 df = df.withColumn("Month",f.month(f.col("CreatedAt")))
194 df = df.withColumn("Year",f.year(f.col("CreatedAt")))
195 df = df.withColumn("Day",f.dayofmonth(f.col("CreatedAt")))
196 df = df.withColumn("subreddit_hash",f.sha2(f.col("subreddit"), 256)[0:3])
198 # next we gotta resort it all.
199 df2 = df.sort(["subreddit","author","id","Year","Month","Day"],ascending=True)
200 df2.write.parquet("/gscratch/comdata/output/reddit_submissions_by_subreddit.parquet", partitionBy=["Year",'Month'], mode='overwrite')
203 # we also want to have parquet files sorted by author then reddit.
204 df3 = df.sort(["author","CreatedAt","subreddit","id","Year","Month","Day"],ascending=True)
205 df3.write.parquet("/gscratch/comdata/output/reddit_submissions_by_author.parquet", partitionBy=["Year",'Month'], mode='overwrite')
207 os.remove("/gscratch/comdata/output/reddit_submissions.parquet_temp")