-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrecommendation.py
More file actions
64 lines (54 loc) · 2.19 KB
/
recommendation.py
File metadata and controls
64 lines (54 loc) · 2.19 KB
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
from collections import defaultdict
from db import execute_query, get_shards, get_shard
class RecommendationEngine:
def __init__(self):
self.shards = get_shards()
def get_recommendations(self, user_id, num_recommendations=5):
try:
product_counts = defaultdict(int)
# Fetch past orders of the user
for shard in self.shards:
query = """
SELECT
oi.product_id, COUNT(*) AS count
FROM
orders o
JOIN
order_items oi ON o.id = oi.order_id
WHERE
o.user_id = %s
GROUP BY
oi.product_id
"""
cursor = execute_query(shard, query, (user_id,))
results = cursor.fetchall()
for product_id, count in results:
product_counts[product_id] += count
# Fetch recent search history of the user
for shard in self.shards:
query = """
SELECT
product_id
FROM
search_history
WHERE
user_id = %s
ORDER BY
search_time DESC
LIMIT %s
"""
cursor = execute_query(shard, query, (user_id, num_recommendations))
results = cursor.fetchall()
for (product_id,) in results:
product_counts[
product_id
] += 1 # Increment count for searched products
# Aggregate recommendations from past orders and recent searches
recommendations = sorted(
product_counts.items(), key=lambda x: x[1], reverse=True
)[:num_recommendations]
return [product_id for product_id, _ in recommendations]
except Exception as e:
print(f"Error occurred while fetching recommendations: {str(e)}")
return []
recommendation_engine = RecommendationEngine()