一个简单明了的 Mapreduce 程序最适合您的方案,以下是供您参考的代码:
以下程序将一次执行 2 个操作:
1) 收集行数据并转换为键值对
2) 消除重复项并仅将不同的值存储到输出,因为键是初始令牌 + 值令牌的组合,因此将通过 reducer 消除重复项。例如 (A|bb) 将是您的键和 null 作为值。
代码:
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
public class MRTranspose extends Configured implements Tool {
public static void main(String args[]) throws Exception {
int res = ToolRunner.run(new MRTranspose(), args);
System.exit(res);
}
public int run(String[] args) throws Exception {
Path inputPath = new Path(args[0]);
Path outputPath = new Path(args[1]);
Configuration conf = getConf();
Job job = new Job(conf, this.getClass().toString());
FileInputFormat.setInputPaths(job, inputPath);
FileOutputFormat.setOutputPath(job, outputPath);
job.setJobName("transpose");
job.setJarByClass(MRTranspose.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(NullWritable.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
return job.waitForCompletion(true) ? 0 : 1;
}
public static class Map extends
Mapper<LongWritable, Text, Text, NullWritable> {
@Override
public void map(LongWritable key, Text value, Mapper.Context context)
throws IOException, InterruptedException {
String line = value.toString();
String words[] = line.split("¦");
for (int i = 1; i < words.length; i++) {
context.write(new Text(words[0] + "¦" + words[i]),
NullWritable.get());
}
}
}
public static class Reduce extends
Reducer<Text, NullWritable, Text, NullWritable> {
@Override
public void reduce(Text key, Iterable<NullWritable> values,
Context context) throws IOException, InterruptedException {
context.write(key, NullWritable.get());
}
}
}
提供原始数据文件夹作为第一个参数,第二个参数作为输出文件夹
输入文件: input.txt
A¦aa¦bb¦cc
A¦bb¦cc¦ac¦dd¦ff¦fg
B¦aa¦ac
输出文件: part-r-00000 文件
A¦aa
A¦ac
A¦bb
A¦cc
A¦dd
A¦ff
A¦fg
B¦aa
B¦ac
最后,将你的 mapreduce 输出路径绑定为你的 hive 表的输入路径,以便进一步查询
希望这是有用的。