This repository has been archived by the owner on May 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
queries.py
566 lines (505 loc) · 14.7 KB
/
queries.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
import time
import datetime
import os
from elasticsearch import Elasticsearch
def main():
host = os.getenv('CONNECTION_STRING')
es: Elasticsearch = Elasticsearch(hosts=host)
query_number: int = int(input("Enter the query number you want to run: "))
print('Result: \n')
startTime = time.perf_counter()
# I wish python had switch cases...
if query_number == 1:
query1(es)
elif query_number == 2:
query2(es)
elif query_number == 3:
query3(es)
elif query_number == 4:
query4(es)
elif query_number == 5:
query5(es)
elif query_number == 6:
query6(es)
elif query_number == 7:
query7(es)
elif query_number == 8:
query8(es)
elif query_number == 9:
query9(es)
elif query_number == 10:
query10(es)
else:
print("Invalid Query Number... Exiting Program...")
finishTime = time.perf_counter()
print(f"Time Taken: {finishTime- startTime}")
def query1(es: Elasticsearch):
"""
What are the top 10 most upvoted comments of all time? Print the comment and the score in an ordered list.
:param es: Elastic Search API
"""
indices = list(es.indices.get_alias().keys())
top_comments = []
query = {
"query_string": {
"query": "*"
}
}
sort = [
{
"score": {
"unmapped_type": "keyword",
"order": "desc"
}
}
]
res = es.search(
index=indices,
query=query,
sort=sort,
size=10
)
comments = res.body["hits"]["hits"]
for comment in comments:
data = comment["_source"]
if len(top_comments) < 10:
top_comments.append(data)
continue
for top_comment in top_comments:
if top_comment["score"] < data["score"]:
top_comments.remove(top_comment)
top_comments.append(data)
for top_comment in top_comments:
print(f"[COMMENT SCORE] {top_comment['score']}\n[COMMENT]: {top_comment['body']}")
print(f"=================================")
print("\n")
def query2(es: Elasticsearch):
"""
How many of the comments listed as controversial are also listed as an edited comment?
:param es: Elastic Search API
"""
indices = list(es.indices.get_alias().keys())
query = {
"bool": {
"must": [
{
"match": {
"controversiality": 1
}
},
{
"match": {
"edited": True
}
}
]
}
}
res = es.search(
index=indices,
query=query,
scroll='2m',
size=1000
)
# Get the scroll ID
sid = res['_scroll_id']
scroll_size = len(res['hits']['hits'])
comments = []
while scroll_size > 0:
"Scrolling..."
# Before scroll, process current batch of hits
##
for item in res['hits']['hits']:
comments.append(item)
data = es.scroll(scroll_id=sid, scroll='2m')
# Update the scroll ID
sid = data['_scroll_id']
# Get the number of results that returned to the last scroll
scroll_size = len(data['hits']['hits'])
total = len(comments)
print(f"total controversial comments: {total}")
def query3(es: Elasticsearch):
"""
What percentage of the controversial comments were made at night (after 10pm)?
:param es: Elastic Search API
"""
indices = list(es.indices.get_alias().keys())
query = {
"match": {
"controversiality": 1
}
}
res = es.search(
index=indices,
query=query,
scroll='2m',
size=1000
)
# Get the scroll ID
sid = res['_scroll_id']
scroll_size = len(res['hits']['hits'])
comments = []
while scroll_size > 0:
"Scrolling..."
# Before scroll, process current batch of hits
##
for item in res['hits']['hits']:
comments.append(item)
data = es.scroll(scroll_id=sid, scroll='2m')
# Update the scroll ID
sid = data['_scroll_id']
# Get the number of results that returned to the last scroll
scroll_size = len(data['hits']['hits'])
total = 0
comments_late = []
for comment in comments:
data = comment['_source']
date = datetime.datetime.fromtimestamp(data['created_utc'])
if date.hour > 22:
total += 1
comments_late.append(data)
print(f"total controversial comments after 10pm: {total}")
for comment in comments_late:
date = datetime.datetime.fromtimestamp(comment['created_utc'])
print(f"[COMMENT TIME]: {date.time()}\n[COMMENT]: {comment['body']}")
print(f"=================================")
print("\n")
def query4(es: Elasticsearch):
"""
What is the percentage of comments with the word sorry in them and are also replying to another comment?
:param es: Elastic Search API
"""
indices = list(es.indices.get_alias().keys())
total: float = 0
total_replies: float = 0
query = {
"match": {
"body": "sorry"
}
}
res = es.search(
index=indices,
query=query,
scroll='2m',
size=1000
)
# Get the scroll ID
sid = res['_scroll_id']
scroll_size = len(res['hits']['hits'])
comments = []
while scroll_size > 0:
"Scrolling..."
# Before scroll, process current batch of hits
##
for item in res['hits']['hits']:
comments.append(item)
data = es.scroll(scroll_id=sid, scroll='2m')
# Update the scroll ID
sid = data['_scroll_id']
# Get the number of results that returned to the last scroll
scroll_size = len(data['hits']['hits'])
total = total + len(comments)
for comment in comments:
data = comment["_source"]
if data['parent_id'] != data['link_id']:
total_replies += 1
if total != 0:
percentage = total_replies / total * 100
print(f"total replies: {total_replies} of total comments: {total} that has the word sorry.")
print("{:.{}f}%".format(percentage, 4))
else:
print("0%")
def query5(es: Elasticsearch):
"""
Who were the top 3 users that commented the most in 2006? How many comments did they make and what was their top commented subreddit?
:param es: Elastic Search API
"""
indices: list[str] = list(es.indices.get_alias().keys())
for index in indices[:]:
if index.find("2007") != -1:
indices.remove(index)
query = {
"match_all": {}
}
aggs = {
"authors": {
"terms": {
"field": "author.keyword",
}
}
}
res = es.search(
index=indices,
query=query,
aggs=aggs,
scroll='2m',
size=1000
)
authors = res.body['aggregations']['authors']['buckets']
for author in authors[:4]:
if author['key'] == '[deleted]':
continue
query = {
"bool": {
"must": [
{
"match": {
"author": author['key']
}
}
]
}
}
sort = [
{
"score": {
"unmapped_type": "keyword",
"order": "desc"
}
}
]
res = es.search(
index=indices,
query=query,
sort=sort,
size=1
)
if res['hits']['hits'][0] is not None:
comment = res['hits']['hits'][0]['_source']
print(f"[Author]: {author['key']} [Count]: {author['doc_count']} [Score]: {comment['score']} "
f"[SubReddit]: {comment['subreddit']} [Comment]: {comment['body']}")
def query6(es: Elasticsearch):
"""
Find all comments about postgres. Display the number of comments that have a score between 15-30. Display the top comment and the lowest comment in that range
:param es: Elastic Search API
"""
indices = list(es.indices.get_alias().keys())
query = {
"bool": {
"must": [
{
"match": {
"body": "postgres"
}
},
{
"range": {
"score": {
"gte": 15,
"lte": 30,
}
}
}
]
}
}
sort = [
{
"score": {
"unmapped_type": "keyword",
"order": "desc"
}
}
]
res = es.search(
index=indices,
query=query,
sort=sort,
size=1000
)
comments = res.body["hits"]["hits"]
print(f"[Total Number of comments]: {len(comments)}")
print(f"[Top Scored Comment in this range]: {comments[0]['_source']['body']}")
print(f"[Lowest Scored Comment in this range]: {comments[-1]['_source']['body']}")
def query7(es):
"""
Display the number of comments for every subreddit and the top comment score. Order them in popularity.
:param es: Elastic Search API
"""
indices = list(es.indices.get_alias().keys())
aggs = {
"numberOfCommentsPerSubreddit": {
"terms": {
"field": "subreddit.keyword",
"size": 1000
},
"aggs": {
"max_value": {
"max": {
"field": "score",
}
}
}
}
}
res = es.search(
index=indices,
aggs=aggs,
size=1000
)
results = res.body['aggregations']['numberOfCommentsPerSubreddit']['buckets']
for result in results:
subreddit = result['key']
total_comments = result['doc_count']
max_comment_score = result['max_value']['value']
print(f"[subreddit]: {subreddit}, [total_comments]: {total_comments}, [top_comment_score]: {max_comment_score}")
def query8(es):
"""
Query every comment between September 2007 and December 2007
that either has the word ‘sql’ or ‘nosql’ in the comment.
Only include comments which have a score greater than 0.
Print the number of comments and print the first 10 results (sorted by score).
:param es: Elastic Search API
"""
indices = ['rc_2007-09', 'rc_2007-10', 'rc_2007-11', 'rc_2007-12']
query = {
"bool": {
"must": [
{
"bool": {
"should": [
{"term": {"body": "sql"}},
{"term": {"body": "nosql"}},
]
}
},
{
"range": {
"score": {
"gte": 1,
}
}
}
]
}
}
sort = [
{
"score": {
"unmapped_type": "keyword",
"order": "desc"
}
}
]
res = es.search(
index=indices,
query=query,
sort=sort,
size=1000
)
results = res.body['hits']['hits']
print(f"total of {len(results)} were comments that either included sql or nosql")
print(f"printing first 10 results:")
for result in results[:11]:
data = result['_source']
print(f"\n[Author]: {data['author']}\n[Subreddit]: {data['subreddit']}"
f"\n[Score]: {data['score']}\n[Comment]: {data['body']}")
def query9(es):
"""
Find the top comment in January 2007, print it and also display the number of replies this comment got in total.
:param es: Elastic Search API
"""
indices = ['rc_2007-01']
query = {
"query_string": {
"query": "*"
}
}
sort = [
{
"score": {
"unmapped_type": "keyword",
"order": "desc"
}
}
]
res = es.search(
index=indices,
query=query,
sort=sort,
size=1
)
top_comment = res.body['hits']['hits'][0]['_source']
print(top_comment)
indices = list(es.indices.get_alias().keys())
query = {
"regexp": {"parent_id": f".*{top_comment['id']}*"}
}
sort = [
{
"created_utc": {
"unmapped_type": "keyword",
"order": "desc"
}
}
]
res = es.search(
index=indices,
query=query,
sort=sort,
size=1000
)
replies = res.body['hits']['hits']
print(f"Total Replies: {len(replies)}")
def query10(es):
"""
Find all comments that mention at least 2 of the following words: sql, database and programming, software. In 2006. State the number of comments
:param es: Elastic Search API
"""
indices: list[str] = list(es.indices.get_alias().keys())
for index in indices[:]:
if index.find("2007") != -1:
indices.remove(index)
query = {
"bool": {
"should": [
{
"term": {
"body": "sql"
}
},
{
"term": {
"body": "database"
}
},
{
"term": {
"body": "programming"
}
},
{
"term": {
"body": "software"
}
}
],
"minimum_should_match": 2
}
}
res = es.search(
index=indices,
query=query,
scroll='5m',
size=1000
)
# Get the scroll ID
sid = res['_scroll_id']
scroll_size = len(res['hits']['hits'])
comments = []
while scroll_size > 0:
"Scrolling..."
# Before scroll, process current batch of hits
##
for item in res['hits']['hits']:
comments.append(item)
data = es.scroll(scroll_id=sid, scroll='5m')
# Update the scroll ID
sid = data['_scroll_id']
# Get the number of results that returned to the last scroll
scroll_size = len(data['hits']['hits'])
total = len(comments)
print(f"total comments that include at least of of the following words: "
f"sql, database, programming, software: {total}")
if __name__ == '__main__':
main()