import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
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.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
public class UserRanking {
public static class TokenizerMapper
extends Mapper<Object, Text, IntWritable, Text>{
private IntWritable steps = new IntWritable();
private Text user = new Text();
public void map(Object key, Text value, Context context
) throws IOException, InterruptedException {
String[] fields = value.toString().split(",");
user.set(fields[0]);
steps.set(Integer.parseInt(fields[1]));
context.write(steps, user);
}
}
public static class IntSumReducer
extends Reducer<IntWritable,Text,Text,IntWritable> {
private int rank = 1;
public void reduce(IntWritable key, Iterable<Text> values,
Context context
) throws IOException, InterruptedException {
for (Text user : values) {
context.write(user, new IntWritable(rank));
rank++;
}
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 2) {
System.err.println("Usage: UserRanking <in> <out>");
System.exit(2);
}
Job job = Job.getInstance(conf, "user ranking");
job.setJarByClass(UserRanking.class);
job.setMapperClass(TokenizerMapper.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
实验代码-1
最新推荐文章于 2024-07-16 13:58:50 发布