PersonalizedRedisService.java 2.64 KB
package com.yoho.search.service.personalized;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.yoho.search.core.personalized.BigDataRedisOper;

/**
 * Created by ginozhang on 2017/1/5.
 */
@Service
public class PersonalizedRedisService {

	// 保存用户特征向量的key格式,比如 “1022102:w2v:20170103” 值是一个字符串,各个值之间用逗号分隔
	private static final String USER_FEATURE_KEY_TEMPLATE = "%s:w2v:%s";
	
	private static final String USER_ACTIVITY_FEATURE_KEY_TEMPLATE = "%s:w2v_f:%s";//活动相关的向量空间【购物车、收藏夹】
	
	private static final String USER_GENDER_KEY= "%s:gender";

	@Autowired
	private BigDataRedisOper<?,?> bigDataRedisOper;

	public String getUserVectorFeature(String uid, String generateDate) {
		String key = String.format(USER_FEATURE_KEY_TEMPLATE, uid, generateDate);
		return bigDataRedisOper.getValue(key);
	}
	
	public String getUserActivityVectorFeature(String uid, String generateDate) {
		String key = String.format(USER_ACTIVITY_FEATURE_KEY_TEMPLATE, uid, generateDate);
		return bigDataRedisOper.getValue(key);
	}
	
	/**
	 * 获取用户性别维度
	 * @param uid
	 * @param generateDate
	 * @return
	 */
	public Map<String,Float> getUserGenderFeature(String uid) {
		String key = String.format(USER_GENDER_KEY, uid);
		String userGenderWeightValue =  bigDataRedisOper.getValue(key);
		if(StringUtils.isBlank(userGenderWeightValue)){
			return new HashMap<String, Float>();
		}
		Map<String,Float> result = new HashMap<String, Float>();
		List<String>  userGenderWeightList = JSONArray.parseArray(userGenderWeightValue, String.class);
		for (String genderWeight : userGenderWeightList) {
			String [] userGenderWeight = genderWeight.split(":");
			result.put(userGenderWeight[0], Float.parseFloat(userGenderWeight[1]));
		}
		return result;
	}
	
	public static void main(String[] args) {
		String userGenderWeightValue = "['2:0.1686046511627907', '1:0.6957364341085271', '3:0.13565891472868216']";
		Map<String,Float> result = new HashMap<String, Float>();
		List<String>  userGenderWeightList = JSONArray.parseArray(userGenderWeightValue, String.class);
		for (String genderWeight : userGenderWeightList) {
			String [] userGenderWeight = genderWeight.split(":");
			result.put(userGenderWeight[0], Float.parseFloat(userGenderWeight[1]));
		}
		for (Map.Entry<String, Float> entry : result.entrySet()) {
			System.out.println(entry.getKey()+ ":" + entry.getValue());
		}
	}

}