-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFinal 1101.py
1031 lines (784 loc) · 34.1 KB
/
Final 1101.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Part 1
## ===============================================================================================================
# Import library
import sqlite3
import json
import requests
import urllib.request
import time
import matplotlib.pyplot as plt
# Define path
url_path = 'http://dbgroup.cdm.depaul.edu/DSC450/OneDayOfTweets.txt'
text_file_path1 = "C:\\Users\\wodnj\\OneDrive\\바탕 화면\Databases for Analytics\\DSC 450 - Week 11\\Data File\\150000_tweets.txt"
text_file_path2 = "C:\\Users\\wodnj\\OneDrive\\바탕 화면\Databases for Analytics\\DSC 450 - Week 11\\Data File\\750000_tweets.txt"
database_path1 = "C:\\Users\\wodnj\\OneDrive\\바탕 화면\\Databases for Analytics\\DSC 450 - Database Files\\Database for Final 1101.db"
database_path2 = "C:\\Users\\wodnj\\OneDrive\\바탕 화면\\Databases for Analytics\\DSC 450 - Database Files\\Database for Final 1102.db"
database_path3 = "C:\\Users\\wodnj\\OneDrive\\바탕 화면\\Databases for Analytics\\DSC 450 - Database Files\\Database for Final 1103.db"
database_path4 = "C:\\Users\\wodnj\\OneDrive\\바탕 화면\\Databases for Analytics\\DSC 450 - Database Files\\Database for Final 1104.db"
database_path5 = "C:\\Users\\wodnj\\OneDrive\\바탕 화면\\Databases for Analytics\\DSC 450 - Database Files\\Database for Final 1105.db"
database_path6 = "C:\\Users\\wodnj\\OneDrive\\바탕 화면\\Databases for Analytics\\DSC 450 - Database Files\\Database for Final 1106.db"
image_file_path = "C:\\Users\\wodnj\\OneDrive\\바탕 화면\\Databases for Analytics\\DSC 450 - Week 11\\Data File\\runtime_comparison.png"
# Part 1-a
## Use Python to download tweets from the web and save them to a local text file
## ===============================================================================================================
def download_tweets_and_save_to_text_file(url_path, text_file_path, tweet_count):
# Record the start time
start_time = time.time()
# Open a text file in write mode
with open(text_file_path, 'w', encoding = 'utf-8') as file:
# Send a GET request to the URL to stream
response = requests.get(url_path, stream = True)
# Initialize tweet counter
count = 0
for line in response.iter_lines(decode_unicode = True):
# Stop processing when reaching a specific tweet count
if count >= tweet_count:
break
try:
tweet = json.loads(line.strip())
file.write(json.dumps(tweet) + '\n')
count += 1
except json.JSONDecodeError:
continue
# Record the end time
end_time = time.time()
# Calculate the runtime
runtime = end_time - start_time
return count, runtime
count1, runtime1 = download_tweets_and_save_to_text_file(url_path, text_file_path1, 150000)
count2, runtime2 = download_tweets_and_save_to_text_file(url_path, text_file_path2, 750000)
print()
print("Part 1-a")
print("-" * 100)
print(f"{count1} tweets have been downloaded")
print(f"{count2} tweets have been downloaded")
print("=" * 100)
# Part 1-b
## Repeat Part 1-a, but populate the 3-table schema that previously created in SQLite
## ===============================================================================================================
def download_tweets_and_populate_to_schema(url_path, database_path, tweet_count):
# Record the start time
start_time = time.time()
# Create User table
User_table = """CREATE TABLE User
(
id INTEGER,
name TEXT,
screen_name TEXT,
description TEXT,
friends_count INTEGER
);"""
# Create Geo table
Geo_Table = """CREATE TABLE Geo
(
type TEXT,
longitude REAL,
latitude REAL,
id TEXT,
CONSTRAINT Geo_PK
PRIMARY KEY(id)
);"""
# Create Tweet table
Tweet_Table = """CREATE TABLE Tweet
(
created_at TEXT,
id_str TEXT,
text TEXT,
source TEXT,
in_reply_to_status_id TEXT,
in_reply_to_user_id TEXT,
in_reply_to_screen_name TEXT,
contributors TEXT,
retweet_count INTEGER,
user_id INTEGER,
geo_id TEXT,
CONSTRAINT Tweet_FK1
FOREIGN KEY(user_id)
REFERENCES User(id),
CONSTRAINT Tweet_FK2
FOREIGN KEY(geo_id)
REFERENCES Geo(id)
);"""
# Connect to the database
conn = sqlite3.connect(database_path)
c = conn.cursor()
# Create the tables
c.execute(User_table)
c.execute(Geo_Table)
c.execute(Tweet_Table)
# Commit all the changes
conn.commit()
# Open the tweet data from the URL
webFD = urllib.request.urlopen(url_path)
# Initialize tweet counter
count = 0
# Flag to insert a default Geo entry
geo_none_inserted = False
for line in webFD:
# Stop processing when reaching a specific tweet count
if count >= tweet_count:
break
try:
tweet = json.loads(line.decode('utf-8').strip())
# Insert record into the User table
c.execute("INSERT INTO User VALUES (?, ?, ?, ?, ?)",
(tweet.get('user', {}).get('id'),
tweet.get('user', {}).get('name'),
tweet.get('user', {}).get('screen_name'),
tweet.get('user', {}).get('description'),
tweet.get('user', {}).get('friends_count')))
# Initialize Geo variables
geo_type = None
longitude = None
latitude = None
geo_id = None
# Get the Geo information
geo = tweet.get('geo')
# Check if Geo information exists
if geo:
geo_type = geo['type']
longitude, latitude = geo['coordinates']
geo_id = f"{longitude}_{latitude}"
# Insert record into the Geo table
c.execute("INSERT OR IGNORE INTO Geo VALUES (?, ?, ?, ?)",
(geo_type,
longitude,
latitude,
geo_id))
elif not geo_none_inserted:
c.execute("INSERT OR IGNORE INTO Geo VALUES (?, ?, ?, ?)",
(None, None, None, None))
geo_none_inserted = True
# Insert record into the Tweet table
c.execute("INSERT INTO Tweet VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(tweet.get('created_at'),
tweet.get('id_str'),
tweet.get('text'),
tweet.get('source'),
tweet.get('in_reply_to_status_id'),
tweet.get('in_reply_to_user_id'),
tweet.get('in_reply_to_screen_name'),
tweet.get('contributors'),
tweet.get('retweet_count'),
tweet.get('user', {}).get('id'),
geo_id))
# Increment the counter
count += 1
except json.JSONDecodeError:
continue
# Commit all the changes
conn.commit()
# Get the row counts for each table
user_count = c.execute("SELECT COUNT(*) FROM User").fetchone()[0]
geo_count = c.execute("SELECT COUNT(*) FROM Geo").fetchone()[0]
tweet_count = c.execute("SELECT COUNT(*) FROM Tweet").fetchone()[0]
# Close the connection
conn.close()
# Record the end time
end_time = time.time()
# Calculate the runtime
runtime = end_time - start_time
return user_count, geo_count, tweet_count, runtime
user_count1, geo_count1, tweet_count1, runtime3 = download_tweets_and_populate_to_schema(url_path, database_path1, 150000)
user_count2, geo_count2, tweet_count2, runtime4 = download_tweets_and_populate_to_schema(url_path, database_path2, 750000)
print()
print("Part 1-b")
print("-" * 100)
print("Row Count of Each Table")
print(f"User table: {user_count1} / Geo table: {geo_count1} / Tweet table: {tweet_count1}")
print(f"User table: {user_count2} / Geo table: {geo_count2} / Tweet table: {tweet_count2}")
print("=" * 100)
# Part 1-c
## Repeat Part 1-b, but use a locally saved tweet file to repeat the database population step
## ===============================================================================================================
def populate_schema_using_local_text_file(text_file_path, database_path, tweet_count):
# Record the start time
start_time = time.time()
# Create User table
User_table = """CREATE TABLE User
(
id INTEGER,
name TEXT,
screen_name TEXT,
description TEXT,
friends_count INTEGER
);"""
# Create Geo table
Geo_Table = """CREATE TABLE Geo
(
type TEXT,
longitude REAL,
latitude REAL,
id TEXT,
CONSTRAINT Geo_PK
PRIMARY KEY(id)
);"""
# Create Tweet table
Tweet_Table = """CREATE TABLE Tweet
(
created_at TEXT,
id_str TEXT,
text TEXT,
source TEXT,
in_reply_to_status_id TEXT,
in_reply_to_user_id TEXT,
in_reply_to_screen_name TEXT,
contributors TEXT,
retweet_count INTEGER,
user_id INTEGER,
geo_id TEXT,
CONSTRAINT Tweet_FK1
FOREIGN KEY(user_id)
REFERENCES User(id),
CONSTRAINT Tweet_FK2
FOREIGN KEY(geo_id)
REFERENCES Geo(id)
);"""
# Connect to the database
conn = sqlite3.connect(database_path)
c = conn.cursor()
# Create the tables
c.execute(User_table)
c.execute(Geo_Table)
c.execute(Tweet_Table)
# Commit changes
conn.commit()
# Open the local file for reading
with open(text_file_path, 'r', encoding = 'utf-8') as file:
# Initialize tweet counter
count = 0
# Flag to insert a default Geo entry
geo_none_inserted = False
for line in file:
# Stop processing when reaching a specific tweet count
if count >= tweet_count:
break
# Parse the tweet
tweet = json.loads(line.strip())
# Insert record into the User table
c.execute("INSERT INTO User VALUES (?, ?, ?, ?, ?)",
(tweet.get('user', {}).get('id'),
tweet.get('user', {}).get('name'),
tweet.get('user', {}).get('screen_name'),
tweet.get('user', {}).get('description'),
tweet.get('user', {}).get('friends_count')))
# Initialize Geo variables
geo_type = None
longitude = None
latitude = None
geo_id = None
# Get the Geo information
geo = tweet.get('geo')
# Check if Geo information exists
if geo:
geo_type = geo['type']
longitude, latitude = geo['coordinates']
geo_id = f"{longitude}_{latitude}"
# Insert record into the Geo table
c.execute("INSERT OR IGNORE INTO Geo VALUES (?, ?, ?, ?)",
(geo_type,
longitude,
latitude,
geo_id))
elif not geo_none_inserted:
c.execute("INSERT OR IGNORE INTO Geo VALUES (?, ?, ?, ?)",
(None, None, None, None))
geo_none_inserted = True
# Insert record into the Tweet table
c.execute("INSERT INTO Tweet VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(tweet.get('created_at'),
tweet.get('id_str'),
tweet.get('text'),
tweet.get('source'),
tweet.get('in_reply_to_status_id'),
tweet.get('in_reply_to_user_id'),
tweet.get('in_reply_to_screen_name'),
tweet.get('contributors'),
tweet.get('retweet_count'),
tweet.get('user', {}).get('id'),
geo_id))
# Increment the counter
count += 1
# Commit all changes and close the connection
conn.commit()
conn.close()
# Record the end time
end_time = time.time()
# Calculate the runtime
runtime = end_time - start_time
return runtime
runtime5 = populate_schema_using_local_text_file(text_file_path1, database_path3, 150000)
runtime6 = populate_schema_using_local_text_file(text_file_path2, database_path4, 750000)
print()
print("Part 1-c")
print("-" * 100)
print("Data population into the schema has been completed")
print("=" * 100)
# Part 1-d
## Repeat the same step with a batching size of 2,500
## ===============================================================================================================
def populate_schema_using_local_text_file_with_batching(text_file_path, database_path, tweet_count, batch_size):
# Record the start time
start_time = time.time()
# Create User table
User_table = """CREATE TABLE User
(
id INTEGER,
name TEXT,
screen_name TEXT,
description TEXT,
friends_count INTEGER
);"""
# Create Geo table
Geo_Table = """CREATE TABLE Geo
(
type TEXT,
longitude REAL,
latitude REAL,
id TEXT,
CONSTRAINT Geo_PK
PRIMARY KEY(id)
);"""
# Create Tweet table
Tweet_Table = """CREATE TABLE Tweet
(
created_at TEXT,
id_str TEXT,
text TEXT,
source TEXT,
in_reply_to_status_id TEXT,
in_reply_to_user_id TEXT,
in_reply_to_screen_name TEXT,
contributors TEXT,
retweet_count INTEGER,
user_id INTEGER,
geo_id TEXT,
CONSTRAINT Tweet_FK1
FOREIGN KEY(user_id)
REFERENCES User(id),
CONSTRAINT Tweet_FK2
FOREIGN KEY(geo_id)
REFERENCES Geo(id)
);"""
# Connect to the database
conn = sqlite3.connect(database_path)
c = conn.cursor()
# Create the tables
c.execute(User_table)
c.execute(Geo_Table)
c.execute(Tweet_Table)
# Commit changes
conn.commit()
# Open the local file for reading
with open(text_file_path, 'r', encoding = 'utf-8') as file:
# Initialize tweet counter
count = 0
# Flag to insert a default Geo entry
geo_none_inserted = False
# Initialize lists for batch inserts
user_batch = []
geo_batch = []
tweet_batch = []
for line in file:
# Stop processing when reaching a specific tweet count
if count >= tweet_count:
break
# Parse the tweet
tweet = json.loads(line.strip())
# Prepare User data
user_batch.append((tweet.get('user', {}).get('id'),
tweet.get('user', {}).get('name'),
tweet.get('user', {}).get('screen_name'),
tweet.get('user', {}).get('description'),
tweet.get('user', {}).get('friends_count')))
# Initialize Geo variables
geo_type = None
longitude = None
latitude = None
geo_id = None
# Get the Geo information
geo = tweet.get('geo')
# Check if Geo information exists
if geo:
geo_type = geo['type']
longitude, latitude = geo['coordinates']
geo_id = f"{longitude}_{latitude}"
# Prepare Geo data
geo_batch.append((geo_type,
longitude,
latitude,
geo_id))
elif not geo_none_inserted:
geo_batch.append((None, None, None, None))
geo_none_inserted = True
# Prepare Tweet data
tweet_batch.append((tweet.get('created_at'),
tweet.get('id_str'),
tweet.get('text'),
tweet.get('source'),
tweet.get('in_reply_to_status_id'),
tweet.get('in_reply_to_user_id'),
tweet.get('in_reply_to_screen_name'),
tweet.get('contributors'),
tweet.get('retweet_count'),
tweet.get('user', {}).get('id'),
geo_id))
# Insert in batches
if len(user_batch) >= batch_size:
c.executemany("INSERT INTO User VALUES (?, ?, ?, ?, ?)", user_batch)
c.executemany("INSERT OR IGNORE INTO Geo VALUES (?, ?, ?, ?)", geo_batch)
c.executemany("INSERT INTO Tweet VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", tweet_batch)
user_batch = []
geo_batch = []
tweet_batch = []
# Increment the counter
count += 1
# Insert any remaining data in User batch
if user_batch:
c.executemany("INSERT INTO User VALUES (?, ?, ?, ?, ?)", user_batch)
# Insert remaining data in Geo batch
if geo_batch:
c.executemany("INSERT OR IGNORE INTO Geo VALUES (?, ?, ?, ?)", geo_batch)
# Insert remaining data in Tweet batch
if tweet_batch:
c.executemany("INSERT INTO Tweet VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", tweet_batch)
# Commit all changes and close the connection
conn.commit()
conn.close()
# Record the end time
end_time = time.time()
# Calculate the runtime
runtime = end_time - start_time
return runtime
runtime7 = populate_schema_using_local_text_file_with_batching(text_file_path1, database_path5, 150000, 2500)
runtime8 = populate_schema_using_local_text_file_with_batching(text_file_path2, database_path6, 750000, 2500)
print()
print("Part 1-d")
print("-" * 100)
print("Data population into the schema using batching has been completed")
print("=" * 100)
# Part 1-e
## Plot the resulting runtimes using matplotlib for Part 1-a, 1-b, 1-c, and 1-d
## ===============================================================================================================
# Define the list of runtimes
runtimes_for_150000_tweets = [runtime1, runtime3, runtime5, runtime7]
runtimes_for_750000_tweets = [runtime2, runtime4, runtime6, runtime8]
# Plot the runtimes
plt.plot(runtimes_for_150000_tweets, marker = 'o', linestyle = '-', color = 'b', label = '150,000 Tweets')
plt.plot(runtimes_for_750000_tweets, marker = 'o', linestyle = '-', color = 'r', label = '750,000 Tweets')
plt.xticks([0, 1, 2, 3], ['1-a', '1-b', '1-c', '1-d'])
plt.ylabel('Runtime (seconds)')
plt.title('Runtime Comparison from 1-a to 1-d')
plt.grid(True)
plt.legend()
plt.savefig(image_file_path)
plt.show()
# Part 2
## ===============================================================================================================
# Import library
import sqlite3
import json
import time
from collections import defaultdict
import re
## Part 2-a
## Write and execute an SQL query to find the minimum longitude and maximum latitude value for each user ID
## ===============================================================================================================
# Write a query based on the given conditions
query = """SELECT Tweet.user_id,
MIN(Geo.longitude) AS min_longitude,
MAX(Geo.latitude) AS max_latitude
FROM Tweet, Geo
WHERE Tweet.geo_id = Geo.id
GROUP BY Tweet.user_id;"""
# Part 2-b
## Re-execute the SQL query in Part 2-a 5 times and 25 times and measure the total runtime
## ===============================================================================================================
def measure_query_runtime1(database_path, query, execution_counts):
# Connect to the database
conn = sqlite3.connect(database_path)
c = conn.cursor()
# Initialize a list to store the runtime for each number of executions
runtime_list = []
# Loop through different numbers of executions to measure the query runtime
for runs in execution_counts:
# Record the start time
start_time = time.time()
for _ in range(runs):
c.execute(query)
# Record the end time
end_time = time.time()
# Calculate the runtime
runtime = end_time - start_time
# Append to the list
runtime_list.append(runtime)
# Commit and close the connection
conn.commit()
conn.close()
return runtime_list
runtimes = measure_query_runtime1(database_path6, query, [5, 25])
print()
print("Part 2-b")
print("-" * 100)
for runs, runtime in zip([5, 25], runtimes):
print(f"Runtime for {runs} executions: {runtime:.2f} seconds")
if runs == 25:
expected_runtime = runtimes[0] * 5
if abs(runtime - expected_runtime) < 0.1 * expected_runtime:
print("Runtime scales linearly")
else:
print("Runtime does not scale linearly")
print("=" * 100)
# Part 2-c
## Write the equivalent of the Part 2-a query in Python by reading it from the file with 750,000 tweets
## ===============================================================================================================
def read_tweets_file(file_path):
# Initialize a defaultdict to store lists of coordinates for each user
records = defaultdict(list)
# Open the file in read mode
with open(file_path, 'r') as file:
# Iterate through each line in the file
for line in file:
# Parse the JSON data from the tweet line
tweet = json.loads(line)
# Extract the user ID and geolocation from the tweet
user_id = tweet.get('user', {}).get('id')
geo = tweet.get('geo')
if geo:
longitude, latitude = geo['coordinates']
records[user_id].append((longitude, latitude))
# Initialize an empty dictionary
result = {}
# Find the minimum longitude and maximum latitude for each user's tweets
for user_id, coordinates in records.items():
min_longitude = min(coordinate[0] for coordinate in coordinates)
max_latitude = max(coordinate[1] for coordinate in coordinates)
result[user_id] = {'MinLongitude': min_longitude, 'MaxLatitude': max_latitude}
return result
# Part 2-d
## Re-execute the query in Part 2-c 5 times and 25 times and measure the total runtime
## ===============================================================================================================
def measure_query_runtime2(file_path, execution_counts):
# Initialize a list to store the runtime for each number of executions
runtime_list = []
# Loop through different numbers of executions to measure the query runtime
for runs in execution_counts:
# Record the start time
start_time = time.time()
for _ in range(runs):
read_tweets_file(file_path)
# Record the end time
end_time = time.time()
# Calculate the runtime
runtime = end_time - start_time
# Append to the list
runtime_list.append(runtime)
return runtime_list
runtimes = measure_query_runtime2(text_file_path2, [5, 25])
print()
print("Part 2-d")
print("-" * 100)
for runs, runtime in zip([5, 25], runtimes):
print(f"Runtime for {runs} executions: {runtime:.2f} seconds")
if runs == 25:
expected_runtime = runtimes[0] * 5
if abs(runtime - expected_runtime) < 0.1 * expected_runtime:
print("Runtime scales linearly")
else:
print("Runtime does not scale linearly")
print("=" * 100)
# Part 2-e
## Write the equivalent of the Part 2-a query in Python by using regular expressions
## ===============================================================================================================
def read_tweets_file_with_regex(file_path):
# Initialize a defaultdict to store lists of coordinates for each user
records = defaultdict(list)
# Define regular expressions
user_id_regex = r'"user":\s*\{"id":\s*(\d+)'
geo_coordinate_regex = r'"geo":\s*\{"type":\s*"Point",\s*"coordinates":\s*\[([\-0-9.]+),\s*([\-0-9.]+)\]\}'
# Open the file in read mode
with open(file_path, 'r') as file:
# Iterate through each line in the file
for line in file:
# Extract the user ID and geolocation from the tweet using regular expressions
user_id_match = re.search(user_id_regex, line)
geo_match = re.search(geo_coordinate_regex, line)
if user_id_match and geo_match:
user_id = int(user_id_match.group(1))
longitude = float(geo_match.group(1))
latitude = float(geo_match.group(2))
records[user_id].append((longitude, latitude))
# Initialize an empty dictionary
result = {}
# Find the minimum longitude and maximum latitude for each user's tweets
for user_id, coordinates in records.items():
min_longitude = min(coordinate[0] for coordinate in coordinates)
max_latitude = max(coordinate[1] for coordinate in coordinates)
result[user_id] = {'MinLongitude': min_longitude, 'MaxLatitude': max_latitude}
return result
# Part 2-f
## Re-execute the query in Part 2-e 5 times and 25 times and measure the total runtime.
## ===============================================================================================================
def measure_query_runtime3(file_path, execution_counts):
# Initialize a list to store the runtime for each number of executions
runtime_list = []
# Loop through different numbers of executions to measure the query runtime
for runs in execution_counts:
# Record the start time
start_time = time.time()
for _ in range(runs):
read_tweets_file_with_regex(file_path)
# Record the end time
end_time = time.time()
# Calculate the runtime
runtime = end_time - start_time
# Append to the list
runtime_list.append(runtime)
return runtime_list
runtimes = measure_query_runtime3(text_file_path2, [5, 25])
print()
print("Part 2-f")
print("-" * 100)
for runs, runtime in zip([5, 25], runtimes):
print(f"Runtime for {runs} executions: {runtime:.2f} seconds")
if runs == 25:
expected_runtime = runtimes[0] * 5
if abs(runtime - expected_runtime) < 0.1 * expected_runtime:
print("Runtime scales linearly")
else:
print("Runtime does not scale linearly")
print("=" * 100)
# Part 3
## ===============================================================================================================
# Import library
import sqlite3
import json
import csv
import os
# Define path
json_file_path = "C:\\Users\\wodnj\\OneDrive\\바탕 화면\Databases for Analytics\\DSC 450 - Week 11\\Data File\\750000_tweets.json"
csv_file_path1 = "C:\\Users\\wodnj\\OneDrive\\바탕 화면\Databases for Analytics\\DSC 450 - Week 11\\Data File"
csv_file_path2 = "C:\\Users\\wodnj\\OneDrive\\바탕 화면\Databases for Analytics\\DSC 450 - Week 11\\Data File\\Tweet.csv"
csv_file_path3 = "C:\\Users\\wodnj\\OneDrive\\바탕 화면\Databases for Analytics\\DSC 450 - Week 11\\Data File\\User.csv"
csv_file_path4 = "C:\\Users\\wodnj\\OneDrive\\바탕 화면\Databases for Analytics\\DSC 450 - Week 11\\Data File\\Geo.csv"
csv_file_path5 = "C:\\Users\\wodnj\\OneDrive\\바탕 화면\Databases for Analytics\\DSC 450 - Week 11\\Data File\\Pre_Join.csv"
## Part 3-a
## Create a new table that corresponds to the join of all tables in the database
## ===============================================================================================================
def create_pre_join_table(database_path):
# Connect to the database
conn = sqlite3.connect(database_path)
c = conn.cursor()
# # Write a query based on the given conditions
query = """CREATE TABLE Pre_Join AS
SELECT User.id AS user_id,
User.name AS user_name,
User.screen_name AS user_screen_name,
User.description AS user_description,
User.friends_count AS user_friends_count,
Geo.type AS geo_type,
Geo.longitude AS geo_longitude,
Geo.latitude AS geo_latitude,
Geo.id AS geo_id,
Tweet.created_at AS tweet_created_at,
Tweet.id_str AS tweet_id_str,
Tweet.text AS tweet_text,
Tweet.source AS tweet_source,
Tweet.in_reply_to_status_id AS tweet_in_reply_to_status_id,
Tweet.in_reply_to_user_id AS tweet_in_reply_to_user_id,
Tweet.in_reply_to_screen_name AS tweet_in_reply_to_screen_name,
Tweet.contributors AS tweet_contributors,
Tweet.retweet_count AS tweet_retweet_count
FROM Tweet
LEFT JOIN User ON Tweet.user_id = User.id
LEFT JOIN Geo ON Tweet.geo_id = Geo.id;"""
# Execute query
c.execute(query)
# Commit and close the connection
conn.commit()
conn.close()
create_pre_join_table(database_path6)
print()
print("Part 3-a")
print("-" * 100)
print("Pre-Join table has been created")
print("=" * 100)
## Part 3-b
## Export the Tweet table, User table, Geo table, and the new PreJoin table from 3-a into a new JSON file
## ===============================================================================================================
def export_tables_to_json(database_path, json_file_path):
# Connect to the database
conn = sqlite3.connect(database_path)
c = conn.cursor()
# Define the list of tables to be exported
tables = ["Tweet", "User", "Geo", "Pre_Join"]
# Dictionary to store table data
data = {}
for table in tables:
# Execute a query
c.execute(f"SELECT * FROM {table}")
# Fetch column names for the current table
columns = [description[0] for description in c.description]
# Fetch all rows from the current table
rows = c.fetchall()
# Combine column names and rows
data[table] = [dict(zip(columns, row)) for row in rows]
# Close the connection
conn.close()
# Write a JSON file
with open(json_file_path, 'w') as json_file:
json.dump(data, json_file)
export_tables_to_json(database_path6, json_file_path)
print()
print("Part 3-b")
print("-" * 100)
print("Contents of tables have been exported to JSON file")
print("=" * 100)
## Part 3-c
## Export the Tweet table, User table, Geo table, and the new PreJoin table from 3-a into a csv file
## ===============================================================================================================
def export_tables_to_csv(database_path, csv_file_path):
# Connect to the database
conn = sqlite3.connect(database_path)
c = conn.cursor()
# Define the list of tables to be exported
tables = ["Tweet", "User", "Geo", "Pre_Join"]
for table in tables:
# Execute a query
c.execute(f"SELECT * FROM {table}")
# Fetch column names for the current table
columns = [description[0] for description in c.description]
# Fetch all rows from the current table
rows = c.fetchall()
# Write to CSV file for each table
file_path = f"{csv_file_path}/{table}.csv"
with open(file_path, 'w', newline = '', encoding = 'utf-8') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(columns)
writer.writerows(rows)
# Close the connection
conn.close()