1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- import { CloudObject, CloudQuery } from "../../../fashion-server/lib/ncloud.js";
- export class RecommendationService {
- constructor() {
- this.perferQuery = new CloudQuery('Perfer'); // 偏好数据存储在 perfer 类中
- }
- /**
- * 获取用户的物品推荐
- * @param userId 用户ID
- * @param howMany 推荐数量
- * @returns 推荐的物品ID列表
- */
- async getItemRecommendations(userId, howMany) {
- // 获取用户的偏好数据
- const userPreferences = await this.getUserPreferences(userId);
- if (!userPreferences || userPreferences.length === 0) {
- return [];
- }
- // 计算物品相似度
- const similarItems = await this.calculateItemSimilarity(userPreferences);
- // 获取推荐物品
- return this.getTopRecommendations(similarItems, howMany);
- }
- /**
- * 获取用户的偏好数据
- * @param userId 用户ID
- * @returns 用户偏好物品的列表
- */
- async getUserPreferences(userId) {
- this.perferQuery.equalTo('user_id', userId); // 查询条件
- const preferences = await this.perferQuery.find(); // 获取用户的偏好数据
- return preferences; // 返回用户偏好物品列表
- }
- /**
- * 计算物品相似度
- * @param userPreferences 用户偏好物品
- * @returns 物品相似度的映射
- */
- async calculateItemSimilarity(userPreferences) {
- const itemSimilarity = new Map();
- // 遍历用户偏好物品,计算与其他物品的相似度
- for (const pref of userPreferences) {
- const itemId = pref.item_id; // 直接访问属性
- const preferenceValue = pref.preference; // 直接访问属性
- // 获取所有物品的偏好数据
- const allPreferences = await this.perferQuery.find();
- for (const otherPref of allPreferences) {
- const otherItemId = otherPref.item_id; // 直接访问属性
- const otherPreferenceValue = otherPref.preference; // 直接访问属性
- if (itemId !== otherItemId) { // 排除自身
- const similarityScore = this.computeSimilarity(preferenceValue, otherPreferenceValue);
- itemSimilarity.set(otherItemId, (itemSimilarity.get(otherItemId) || 0) + similarityScore);
- }
- }
- }
- return itemSimilarity;
- }
- /**
- * 计算两个物品之间的相似度
- * @param preference1 第一个物品的偏好值
- * @param preference2 第二个物品的偏好值
- * @returns 相似度分数
- */
- computeSimilarity(preference1, preference2) {
- // 示例:使用简单的相似度计算(如绝对值差)
- return Math.abs(preference1 - preference2); // 这里是一个简单的示例
- }
- /**
- * 获取前 N 个推荐物品
- * @param similarItems 物品相似度映射
- * @param howMany 推荐数量
- * @returns 推荐物品ID列表
- */
- getTopRecommendations(similarItems, howMany) {
- // 将相似度映射转换为数组并排序
- const sortedItems = Array.from(similarItems.entries()).sort((a, b) => b[1] - a[1]);
- // 获取前 N 个物品ID
- return sortedItems.slice(0, howMany).map(item => item[0]);
- }
- }
- // 使用示例
- let recommendationService = new RecommendationService();
- recommendationService.getItemRecommendations('266024222614683648', 2).then(result => {
- console.log(result);
- }).catch(error => {
- console.error("Error fetching recommendations:", error);
- });
|