-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.py
70 lines (55 loc) · 1.52 KB
/
database.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
import pymongo
import os
from bson import ObjectId
import numpy as np
mongodb_url = ""
client = pymongo.MongoClient(mongodb_url)
Db = 'amazon_product'
collection = 'product'
db = client[Db]
col = db[collection]
def GetProduct(limit=100):
pipeline = [
{"$sample": {"size": limit}},
]
return list(col.aggregate(pipeline))
def GetProductById(id):
projection = {'plot_embedding': False}
return col.find_one({'product_id': id})
def vectorSearch(title,limit=10):
result=db.product.aggregate([
{
"$vectorSearch": {
"index": "vector_index",
"path": "plot_embedding",
"queryVector": title,
"numCandidates": 100,
"limit": limit
}
}
])
return list(result)
def homeRecommendation(clicked_product_ids, limit=10):
embeddings = []
for product_id in clicked_product_ids:
product = GetProductById(int(product_id))
if product and 'plot_embedding' in product:
embeddings.append(product['plot_embedding'])
avg_embedding = np.mean(embeddings, axis=0).tolist()
result = db.product.aggregate([
{
"$vectorSearch": {
"index": "vector_index",
"path": "plot_embedding",
"queryVector": avg_embedding,
"numCandidates": 100,
"limit": limit
}
},
{
"$project": {
"plot_embedding": 0
}
}
])
return list(result)