packagecom.mahout.helloworlddemo;importjava.sql.Connection;importjava.sql.DatabaseMetaData;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;importjava.util.HashSet;importjava.util.List;importorg.apache.mahout.cf.taste.impl.model.jdbc.MySQLJDBCDataModel;importorg.apache.mahout.cf.taste.impl.neighborhood.NearestNUserNeighborhood;importorg.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender;importorg.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;importorg.apache.mahout.cf.taste.model.DataModel;importorg.apache.mahout.cf.taste.model.JDBCDataModel;importorg.apache.mahout.cf.taste.neighborhood.UserNeighborhood;importorg.apache.mahout.cf.taste.recommender.RecommendedItem;importorg.apache.mahout.cf.taste.recommender.Recommender;importorg.apache.mahout.cf.taste.similarity.UserSimilarity;importcom.mahout.util.DBUtil;importcom.mysql.jdbc.jdbc2.optional.MysqlDataSource;/***
*@authorwxisme
*@time 2015-9-13 下午6:25:26*/
public classRecommenderIntroFromMySQL {public static void main(String[] args) throwsException {//连接MySQL
MysqlDataSource dataSource = newMysqlDataSource();
dataSource.setServerName("localhost");
dataSource.setUser("root");
dataSource.setPassword("1234");
dataSource.setDatabaseName("mahoutdemo");//获取数据模型
JDBCDataModel dataModel = new MySQLJDBCDataModel(dataSource, "taste_preferences", "user_id", "item_id", "preference","time");
DataModel model=dataModel;//计算相似度
UserSimilarity similarity = newPearsonCorrelationSimilarity(model);//计算阈值
UserNeighborhood neighborhood = new NearestNUserNeighborhood(2,similarity,model);//推荐
Recommender recommender = newGenericUserBasedRecommender(model,neighborhood,similarity);
Connection con=DBUtil.getConnection();
Statement stmt=con.createStatement();//获取每个用户的推荐数据并存入数据库
for(int i=0; i<5; i++) {
List recommendations = recommender.recommend(i, 3);
String tableName= "user_" +i;for(RecommendedItem recommendation : recommendations) {//如果是第一次推荐就创建该用户的数据表
if(!doesTableExist(tableName)) {
String createSQL= "create table " +tableName+ " (item_id bigint primary key,value float);";
stmt.execute(createSQL);
}
String insertSQL= "insert into " + tableName + " values ("
+ recommendation.getItemID() + "," + recommendation.getValue() + " );";//插入用户的推荐数据
stmt.execute(insertSQL);
System.out.println(recommendation);
}
}
}/*** 是否存在这个数据表
*@paramtablename
*@return*@throwsSQLException*/
public static Boolean doesTableExist(String tablename) throwsSQLException {
HashSet set = new HashSet();
Connection con=DBUtil.getConnection();
DatabaseMetaData meta=con.getMetaData();
ResultSet res= meta.getTables(null, null, null,new String[]{"TABLE"});while(res.next()) {
set.add(res.getString("TABLE_NAME"));
}
DBUtil.close(res, con);returnset.contains(tablename);
}
}