MapReduce学习之好友推荐

时间:2021-08-18 21:56:29

背景

在QQ,微博等社交软件中都会有好友推荐的功能,本案例将使用MapReduce 实现一个简单的好友推荐的功能。想象一下,程序如何推荐好友呢?假设A和B为好友关系,B和C为好友关系,那么我们就假定A和C有好友关系。更复杂的情况,A和B、C均为好友关系,B、C和D均为好友关系,那么我们就假定A和D有好友关系。这样的关系可以称为二度关系。在实际过程中可以判断这种二度关系的数量进行好友推荐,或者进行三度关系的数量判断来进行推荐。

分析

数据如下形式:
A B
B C
C D
B E
A D

map阶段可以得到如下格式:
Key:A Value:B D
Key:B ValueC E
Key:C ValueD
reduce阶段可以将value进行笛卡尔积运算就可以得到二度关系。

代码实现

java实现如下

map 函数体:
protected void map(LongWritable key, Text value,
Mapper<LongWritable, Text, Text, Text>.Context context)
throws java.io.IOException, InterruptedException {

String line = value.toString();
String[] ss = line.split("\t");

context.write(new Text(ss[0]), new Text(ss[1]));
context.write(new Text(ss[1]), new Text(ss[0]));

};
reduce 函数体:
protected void reduce(Text key, java.lang.Iterable<Text> value,
Reducer<Text, Text, Text, Text>.Context context)
throws java.io.IOException, InterruptedException {

Set<String> set = new HashSet<String>();
for(Text v : value ){
set.add(v.toString());
}

if(set.size() > 1){
for (Iterator j = set.iterator(); j.hasNext();) {
String name = (String) j.next();
for (Iterator i = set.iterator(); i.hasNext();) {
String other = (String) i.next();
if(!name.equals(other)){
context.write(new Text(name), new Text(other));
}
}
}
}

};

运行结果如下
MapReduce学习之好友推荐
MapReduce学习之好友推荐

reduce阶段完成笛卡尔积运算的时候,可以用多种算法可以提高速度,这里只是简单的实现。