-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart5.py
300 lines (262 loc) · 10.2 KB
/
part5.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
import csv
from pymongo import MongoClient
import time
# Connect to MongoDB
db_name = "demodb"
client = MongoClient('localhost', 6001, directConnection=True)
client2 = MongoClient('localhost', 7001, directConnection=True)
db = client[db_name]
db2 = client2[db_name]
csv_files = [
"authentication.csv",
"billing.csv",
"content_repository.csv",
"geolocation.csv",
"logging.csv",
"server_locations.csv",
"streaming_metadata.csv",
"user_preferences.csv",
"user_profiles.csv",
"viewing_history.csv"
]
unique_genres = [
"Crime",
"Comedy",
"Action",
"Children",
"Drama",
"Adventure",
"Thriller",
"Documentary",
"Horror",
"Mystery",
"Romance",
]
def read_csv_and_insert(file_path, collection_name):
# Read CSV file and insert data into MongoDB
with open(file_path, 'r') as csvfile:
reader = csv.DictReader(csvfile)
data = [row for row in reader]
# Insert data into MongoDB collection
if(collection_name == 'content_repository'):
for movie in data:
if(movie['genre'] in unique_genres[:5]):
collection = db[collection_name]
collection.insert_one(movie)
else:
collection = db2[collection_name]
collection.insert_one(movie)
return
collection = db[collection_name]
result = collection.insert_many(data)
print(f"Inserted {len(result.inserted_ids)} documents.")
def find_data(collection_name, query={}):
# Find documents in MongoDB collection
if(collection_name == 'content_repository'):
collection = db[collection_name]
result = collection.find(query)
print("First searching in Cluster 1...")
print("Data in database Cluster 1:")
for document in result:
print(document)
print("Now searching in Cluster 2...")
collection = db2[collection_name]
result = collection.find(query)
print("Data in database Cluster 2:")
for document in result:
print(document)
return
collection = db[collection_name]
result = collection.find(query)
print("Data in database:")
for document in result:
print(document)
def update_data(query, update_data, collection_name):
# Update documents in MongoDB collection
if(collection_name == 'content_repository'):
print("First searching in Cluster 1 and updating if found...")
collection = db[collection_name]
result = collection.update_many(query, {'$set': update_data})
print(f"Matched {result.matched_count} documents and modified {result.modified_count} documents.")
print("Now searching in Cluster 2 and updating if found...")
collection = db2[collection_name]
result = collection.update_many(query, {'$set': update_data})
print(f"Matched {result.matched_count} documents and modified {result.modified_count} documents.")
return
collection = db[collection_name]
result = collection.update_many(query, {'$set': update_data})
print(f"Matched {result.matched_count} documents and modified {result.modified_count} documents.")
def delete_data(query, collection_name):
# Delete documents in MongoDB collection
if(collection_name == 'content_repository'):
print("First searching in Cluster 1 and deleting if found...")
collection = db[collection_name]
result = collection.delete_many(query)
print(f"Deleted {result.deleted_count} documents.")
print("Now searching in Cluster 2 and deleting if found...")
collection = db2[collection_name]
result = collection.delete_many(query)
print(f"Deleted {result.deleted_count} documents.")
return
collection = db[collection_name]
result = collection.delete_many(query)
print(f"Deleted {result.deleted_count} documents.")
# Optimized function
def optimized_query(collection_name):
start_time = time.time()
pipeline = [
{
"$lookup": {
"from": "geolocation",
"localField": "user_id",
"foreignField": "user_id",
"as": "geolocation_data"
}
},
{
"$match": {
"genre_pref": {"$ne": ""}
}
},
{
"$project": {
"genres": {"$split": ["$genre_pref", "|"]},
"geolocation_data.geolocation_id": 1
}
},
{"$unwind": "$genres"},
{"$unwind": "$geolocation_data"},
{
"$group": {
"_id": {
"genre": "$genres",
"geolocation_id": "$geolocation_data.geolocation_id"
},
"genre_count": {"$sum": 1}
}
},
{
"$sort": {"genre_count": -1}
}
]
results = list(collection_name.aggregate(pipeline))
end_time = time.time()
print("<><><><><><><><><><><><><><><>")
print(f"Optimized query execution time: {end_time - start_time} seconds")
print("<><><><><><><><><><><><><><><>")
return results
# Non-Optimized function
def non_optimized_query(collection_name):
start_time = time.time()
pipeline = [
{
"$match": {
"genre_pref": {"$ne": ""}
}
},
{
"$project": {
"user_id": 1,
"genres": {"$split": ["$genre_pref", "|"]}
}
},
{"$unwind": "$genres"},
{
"$lookup": {
"from": "geolocation",
"localField": "user_id",
"foreignField": "user_id",
"as": "geolocation_data"
}
},
{"$unwind": "$geolocation_data"},
{
"$group": {
"_id": {
"genre": "$genres",
"geolocation_id": "$geolocation_data.geolocation_id"
},
"genre_count": {"$sum": 1}
}
},
{
"$sort": {"genre_count": -1}
}
]
results = list(collection_name.aggregate(pipeline))
end_time = time.time()
print("<><><><><><><><><><><><><><><>")
print(f"Unoptimized query execution time: {end_time - start_time} seconds")
print("<><><><><><><><><><><><><><><>")
return results
def initial_data_load():
for csv_file in csv_files:
delete_data({}, collection_name=csv_file.split(".")[0])
for csv_file in csv_files:
csv_file_path = f"./datasets/{csv_file}"
collectionname = csv_file.split(".")[0]
read_csv_and_insert(csv_file_path, collection_name=collectionname)
def find_document_in_collection():
print("Collection:\n0. Authentication\n1. Billing\n2. Content Repository\n3. Geolocation\n4. Logging\n5. Server Locations\n6. Streaming Metadata\n7. User Preferences\n8. User Profiles\n9. Viewing History")
s_coll = int(input("Enter index of collection to search in from the list above(0-9): "))
collectionname = csv_files[s_coll].split(".")[0]
s_key = input("Enter the key to search: ")
s_value = input("Enter the value to search: ")
if not s_key or not s_value:
query = {}
else:
query = {s_key: s_value}
find_data(collection_name=collectionname, query=query)
def update_document_in_collection():
print("Collection:\n0. Authentication\n1. Billing\n2. Content Repository\n3. Geolocation\n4. Logging\n5. Server Locations\n6. Streaming Metadata\n7. User Preferences\n8. User Profiles\n9. Viewing History")
s_coll = int(input("Enter index of collection to search in from the list above(0-9): "))
collectionname = csv_files[s_coll].split(".")[0]
s_key = input("Enter the key to filter a document with: ")
s_oldvalue = input("Enter the value of the key to filter a document with: ")
s_keynew = input("Enter the key to update the value of: ")
s_newvalue = input("Enter the new value: ")
if not s_key or not s_oldvalue or not s_keynew or not s_newvalue:
print("No valid input detected. Need a valid key, old value and new value to do an update operation")
return
update_query = {s_key: s_oldvalue}
new_data = {s_keynew: s_newvalue}
update_data(update_query, new_data, collection_name=collectionname)
def delete_document_in_collection():
print("Collection:\n0. Authentication\n1. Billing\n2. Content Repository\n3. Geolocation\n4. Logging\n5. Server Locations\n6. Streaming Metadata\n7. User Preferences\n8. User Profiles\n9. Viewing History")
s_coll = int(input("Enter index of collection to search in from the list above(0-9): "))
collectionname = csv_files[s_coll].split(".")[0]
s_key = input("Enter the key to delete the value of: ")
s_value = input("Enter the value to delete: ")
if not s_key or not s_value:
print("No valid input detected. Need a valid key and value to do a delete operation")
return
delete_query = {s_key: s_value}
delete_data(delete_query, collection_name=collectionname)
if __name__ == "__main__":
ans = 'y'
while(ans == 'y'):
print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
print("")
print("Choose an option from the following")
print('1. Initial data load from CSVs')
print('2. Find document in a collection')
print('3. Update document in a collection')
print('4. Delete document in a collection')
print('5. Demonstrate query optimization')
print('6. Exit')
choice = int(input("Enter choice (1-6): "))
if(choice == 1):
initial_data_load()
elif(choice == 2):
find_document_in_collection()
elif(choice == 3):
update_document_in_collection()
elif(choice == 4):
delete_document_in_collection()
elif(choice == 5):
unoptimised_result = non_optimized_query(db["user_preferences"])
print("Unoptimized result <truncated>: ", unoptimised_result)
optimised_result = optimized_query(db["user_preferences"])
print("Optimized result <truncated>: ", optimised_result)
elif(choice == 6):
ans = 'n'