从Hadoop Mapper中采样记录

时间:2013-06-19 22:06:46

标签: hadoop hadoop-streaming

我有一个数据集,其键由3部分组成:a,b和c。在我的映射器中,我想发出记录,键为“a”,值为“a,b,c”

如何为Hadoop中的映射器检测到的每个'a'发出10%的总记录?是否应该考虑从临时文件中的先前Map-Reduce作业中保存每个'a'所看到的记录总数?

2 个答案:

答案 0 :(得分:0)

如果你想要接近10%,你可以使用随机。以下是Mapper的一个示例:

public class Test extends Mapper<LongWritable, Text, LongWritable, Text> {

    private Random r = new Random();

    @Override
    public void map(LongWritable key, Text value, Context context)
            throws IOException, InterruptedException {
        if (r.nextInt(10) == 0) {
            context.write(key, value);
        }
    }

}

答案 1 :(得分:0)

使用此java代码随机选择10%:

import java.io.IOException;
import java.util.*;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
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;

public class RandomSample {

 public static class Map extends Mapper<LongWritable, Text, Text, Text> {
    private Text word = new Text();

    public void map(LongWritable key, Text value, Context context)
    throws IOException, InterruptedException {
        if (Math.random()<0.1)
            context.write(value,null);
        else
            context.write(null,null);
    context.write(value,null);
    } 
 }

 public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();

    Job job = new Job(conf, "randomsample");
    job.setJarByClass(RandomSample.class);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(Text.class);
    job.setInputFormatClass(TextInputFormat.class);
    job.setOutputFormatClass(TextOutputFormat.class);

    job.setNumReduceTasks(0);

    FileInputFormat.addInputPath(job, new Path(args[0]));
    FileOutputFormat.setOutputPath(job, new Path(args[1]));

    job.waitForCompletion(true);
 }

}

并使用此bash脚本运行它

echo "Running Job"
hadoop jar RandomSample.jar RandomSample $1 tmp
echo "copying result to local path (RandomSample)"
hadoop fs -getmerge tmp RandomSample
echo "Clean up"
hadoop fs -rmr tmp

例如,如果我们将脚本命名为random_sample.sh,要从文件夹/example/中选择10%,只需运行

./random_sample.sh /example/