
MySQL
Javaimport Java.io.IOException;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.FloatWritable;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;public class StudentAverageScore { public static class ScoreMapper extends Mapper<Object, Text, Text, IntWritable>{ private Text name = new Text(); private IntWritable score = new IntWritable(); public void map(Object key, Text value, Context context) throws IOException, InterruptedException { String[] fields = value.toString().split(","); name.set(fields[0]); score.set(Integer.parseInt(fields[2])); context.write(name, score); } } public static class AverageReducer extends Reducer<Text, IntWritable, Text, FloatWritable>{ private FloatWritable average = new FloatWritable(); public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; int count = 0; for (IntWritable value : values) { sum += value.get(); count++; } float avg = (float) sum / count; average.set(avg); context.write(key, average); } } public static void mAIn(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "Student Average Score"); job.setJarByClass(StudentAverageScore.class); job.setMapperClass(ScoreMapper.class); job.setReducerClass(AverageReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.wAItForCompletion(true) ? 0 : 1); }}以上代码使用了Hadoop的MapReduce模型来计算每个学生的平均成绩。Mapper将输入数据按照学生姓名和成绩进行映射,Reducer则计算每个学生的成绩总和并求平均值。最终的结果将保存在输出文件中。通过比较Hadoop和MySQL在处理和查询独立结构化数据负载方面的特点,我们可以根据实际需求选择合适的技术和工具来处理和管理数据。对于大规模数据处理和存储,Hadoop具有明显的优势;而对于小规模数据集和实时查询场景,MySQL和Postgres更具优势。Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号