该功能是基于数据库中persona_order表实现的,该表记录了用户的id以及该用户购买过的商品,主要思路如下:
package bubugao.com.productRecommendation;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/*
* function:创建买了又买的模型,并将模型导入数据库
* author:shiwei
*/
public class BuyAgain {
protected Map<String,HashMap<String,Integer>> dataMap;//对应用户及其所购买过的商品和数量
protected static HashMap<String,ArrayList<String>> proUsersMap;//对应商品及其购买该商品的用户
protected HashSet<String> productsIdSet;//商品id集
protected HashMap<String,String> products;//商品id_name
protected static LinkedHashMap<String,Float> userTreeMap;//基于用户比例,保存对应的结果,--productId_ratio
protected static LinkedHashMap<String,Float> itemTreeMap;//基于商品比例,保存对应的结果,--productId_ratio
ArrayList<String> productTopNIds;
public static void main(String[] args) {
// TODO Auto-generated method stub
String tableName="bi_product_order_product";
new BuyAgain().modelImport(tableName,30);
}
public BuyAgain(){
long time1=System.currentTimeMillis();
this.getDataMap();
long time2=System.currentTimeMillis();
System.out.println("获取数据库所需时间"+(time2-time1)+"ms");
this.getProUsersMap();
long time3=System.currentTimeMillis();
System.out.println("固定统计p_users的时间"+(time3-time1)+"ms");
}
//基于用户比例推荐商品
public void buyAgainByUser(String productId,int topN){
ArrayList<String> userList=this.getUsersByProductId(productId);
HashMap<String,Float> productsNUserRatioMap=this.getProductsUserRatioMap(userList,productId);
userTreeMap=this.getTopNProductsMap(productsNUserRatioMap, topN);
}
//基于商品比例推荐商品
public void buyAgainByProduct(String productId,int topN){
ArrayList<String> userList=this.getUsersByProductId(productId);
HashMap<String,Integer> productNumMap=this.getProductsMap(userList,productId);
HashMap<String,Float> productsNumRatioMap=this.getProductsNumRatioMap(productNumMap);
itemTreeMap=this.getTopNProductsMap(productsNumRatioMap, topN);
}
//从数据库中获取数据,存入Map中
public void getDataMap(){
dataMap=new HashMap<String,HashMap<String,Integer>>();
products=new HashMap<String,String>();
JDBCConnection jc=new JDBCConnection();
jc.startMySQLConn();
String sql