背景
在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 Value:C E
Key:C Value:D
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));
}
}
}
}
};
運行結果如下:
reduce
階段完成笛卡爾積運算的時候,可以用多種算法可以提高速度,這裏只是簡單的實現。