我创建了一个名为textarraywritable的子类来保存一个文本数组。看起来是这样的:
import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.Text;
public class TextArrayWritable extends ArrayWritable{
public TextArrayWritable() {
super(Text.class);
}
public TextArrayWritable(Text[] values) {
super(Text.class,values);
}
}
在我的Map器中,我生成一个键-值对,其中键是文本,值是上面的textarraywritable。Map器的代码如下所示:
import java.io.IOException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class TagWordMapper extends Mapper<LongWritable,Text,Text,TextArrayWritable>{
@Override
public void map(LongWritable key,Text value,Context context) throws IOException, InterruptedException{
if(key.get()==0) {
return;
}else {
String line = value.toString();
Text title = new Text(line.split("\t")[2]);
Text likes = new Text(line.split("\t")[8]);
Text tags = new Text(line.split("\t")[6]);
Text[] temp = new Text[2];
temp[0]=likes;
temp[1]=tags;
context.write(title, new TextArrayWritable(temp));
}
}
}
这个问题发生在reducer中,当我循环遍历textarraywritable时,即使我将其转换为text[],异常也会发生,因为textarraywritable#get()返回文本数组。减速器代码如下:
import java.io.IOException;
import java.util.regex.*;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Reducer;
public class TagWordCombiner extends Reducer<Text,TextArrayWritable,Text,IntWritable>{
@Override
public void reduce(Text title,Iterable<TextArrayWritable> arrays,Context context) throws IOException, InterruptedException{
int count=0;
Pattern r = Pattern.compile("\\bcute\\b",Pattern.CASE_INSENSITIVE);
for(TextArrayWritable array:arrays) {
Text[] temp = (Text[]) array.get();
int likes = Integer.parseInt(temp[0].toString());
String tags = temp[1].toString();
Matcher matcher = r.matcher(tags);
boolean found = matcher.find();
if(found && likes>=3000){
count+=1;
}
}
context.write(title, new IntWritable(count));
}
}
即使我将返回类型转换为text[],也不知道为什么会发生这种情况。任何见解都是值得赞赏的。谢谢你的阅读。
1条答案
按热度按时间1bqhqjot1#
我决定不使用textarraywritable,而是选择使用文本以字符串形式发送数据数组。此外,我发现合并器的工作。组合器的输入/输出数据类型必须与Map器的输出数据类型匹配。
这是我的密码:
Map器:
它所做的,它Map了一个
.csv
文件。它跳过第一行,因为第一行是标题,没有用。在下一行中,它按“\t”拆分以按顺序提取“title”、“likes”、“tags”。只有“likes”和“tags”要插入到数组中。Map器输出数据类型为text,text。合路器:
组合器如何工作的一个棘手问题是,它的输入/输出必须与Map器的输出数据类型匹配,否则它将抛出我遇到的错误。在本例中,我使用combiner作为一个过滤器,过滤掉那些没有>=3000赞的标题,并且它的标签不包含任何形式的单词cute。它输入为<text,text>数据类型,输出为<text,text>数据类型,两者都与Map器的输出数据类型相同。
最后,减速器:
它的功能就像一个规则的减缩器,它对数组中的数据求和并产生最终的和。循环遍历iterable是毫无意义的,因为它是在combiner中为我们完成的,但它是有效的。
这是我的驾驶课:
注意combiner类,在mapper和reducer类之间。另外,请确保包含setmapoutputkeyclass和setmapoutputvalueclass。这允许Map器类的不同输出数据类型。它还强制reducer输出数据类型为您为setoutputkeyclass和setoutputvalueclass设置的任何类型,在我们的示例中,reducer必须输出文本和intwritable。
如果有任何问题,请发表评论。关于hadoop的信息有点少。