24.10.31
实验5
MapReduce初级编程实践
1.实验目的
(1)通过实验掌握基本的MapReduce编程方法;
(2)掌握用MapReduce解决一些常见的数据处理问题,包括数据去重、数据排序和数据挖掘等。
2.实验平台
(1)操作系统:Linux(建议Ubuntu16.04或Ubuntu18.04)
(2)Hadoop版本:3.1.3
3.实验步骤
(一)编程实现文件合并和去重操作
对于两个输入文件,即文件A和文件B,请编写MapReduce程序,对两个文件进行合并,并剔除其中重复的内容,得到一个新的输出文件C。下面是输入文件和输出文件的一个样例供参考。
输入文件A的样例如下:
20170101 x
20170102 y
20170103 x
20170104 y
20170105 z
20170106 x
输入文件B的样例如下:
20170101 y
20170102 y
20170103 x
20170104 z
20170105 y
根据输入文件A和B合并得到的输出文件C的样例如下:
20170101 x
20170101 y
20170102 y
20170103 x
20170104 y
20170104 z
20170105 y
20170105 z
20170106 x
package org.example.mapreduce;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
public class MergeAndDeduplicateMapper extends Mapper<LongWritable, Text, Text, Text> {
private Text line = new Text();
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
// 直接将每行内容作为键输出
line.set(value.toString());
context.write(line, new Text(""));
}
}
package org.example.mapreduce;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
public class MergeAndDeduplicateReducer extends Reducer<Text, Text, Text, Text> {
@Override
protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
// 去重只需输出唯一的key
context.write(key, null);
}
}
package org.example.mapreduce;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class MergeAndDeduplicateDriver {
public static void main(String[] args) throws Exception {
// 本地输入文件和输出文件
String localInputFileA = "src/main/java/org/example/mapreduce/fileA.txt";
String localInputFileB = "src/main/java/org/example/mapreduce/fileB.txt";
String localOutputDir = "output_local/";
// HDFS输入输出路径
String hdfsInputDir = "/user/hadoop/input/";
String hdfsOutputDir = "/user/hadoop/output/";
// 配置Hadoop文件系统
Configuration conf = new Configuration();
System.setProperty("HADOOP_USER_NAME","hadoop");
conf.set("fs.defaultFS", "hdfs://192.168.70.143:8020");
FileSystem fs = FileSystem.get(conf);
// 1. 上传本地文件到HDFS
uploadToHDFS(fs, localInputFileA, hdfsInputDir + "fileA.txt");
uploadToHDFS(fs, localInputFileB, hdfsInputDir + "fileB.txt");
// 2. 设置MapReduce作业
Job job = Job.getInstance(conf, "Merge and Deduplicate Files");
job.setJarByClass(MergeAndDeduplicateDriver.class);
job.setMapperClass(MergeAndDeduplicateMapper.class);
job.setReducerClass(MergeAndDeduplicateReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
// 设置输入和输出路径
FileInputFormat.addInputPath(job, new Path(hdfsInputDir + "fileA.txt"));
FileInputFormat.addInputPath(job, new Path(hdfsInputDir + "fileB.txt"));
FileOutputFormat.setOutputPath(job, new Path(hdfsOutputDir));
// 3. 提交任务并等待完成
boolean success = job.waitForCompletion(true);
if (!success) {
System.err.println("Job failed!");
System.exit(1);
}
// 4. 下载输出文件到本地
downloadFromHDFS(fs, hdfsOutputDir + "/part-r-00000", localOutputDir + "result.txt");
System.out.println("Job completed successfully. Output file is saved to: " + localOutputDir + "result.txt");
// 5. 删除HDFS中的临时目录
fs.delete(new Path(hdfsInputDir), true);
fs.delete(new Path(hdfsOutputDir), true);
}
// 上传文件到HDFS
private static void uploadToHDFS(FileSystem fs, String localPath, String hdfsPath) throws IOException {
Path src = new Path(localPath);
Path dest = new Path(hdfsPath);
fs.copyFromLocalFile(false, true, src, dest);
System.out.println("Uploaded: " + localPath + " to " + hdfsPath);
}
// 从HDFS下载文件到本地
private static void downloadFromHDFS(FileSystem fs, String hdfsPath, String localPath) throws IOException {
Path src = new Path(hdfsPath);
File localFile = new File(localPath);
localFile.getParentFile().mkdirs(); // 确保本地目录存在
try (
FSDataInputStream inputStream = fs.open(src);
FileOutputStream outputStream = new FileOutputStream(localFile)
) {
byte[] buffer = new byte[4096]; // 缓冲区大小
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, bytesRead);
}
}
System.out.println("Downloaded: " + hdfsPath + " to " + localPath);
}
}
(二)编写程序实现对输入文件的排序
现在有多个输入文件,每个文件中的每行内容均为一个整数。要求读取所有文件中的整数,进行升序排序后,输出到一个新的文件中,输出的数据格式为每行两个整数,第一个数字为第二个整数的排序位次,第二个整数为原待排列的整数。下面是输入文件和输出文件的一个样例供参考。
输入文件1的样例如下:
33
37
12
40
输入文件2的样例如下:
4
16
39
5
输入文件3的样例如下:
1
45
25
根据输入文件1、2和3得到的输出文件如下:
1 1
2 4
3 5
4 12
5 16
6 25
7 33
8 37
9 39
10 40
11 45
package org.example.mapreduce;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
public class SortMapper extends Mapper<LongWritable, Text, IntWritable, IntWritable> {
private IntWritable number = new IntWritable();
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
// 将每行内容转为整数
number.set(Integer.parseInt(value.toString().trim()));
// 输出整数值作为键,值为1(无意义)
context.write(number, new IntWritable(1));
}
}
package org.example.mapreduce;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
public class SortReducer extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> {
private IntWritable rank = new IntWritable(1); // 排序位次
@Override
protected void reduce(IntWritable key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
// 对排序后的整数逐一输出
context.write(rank, key);
rank.set(rank.get() + 1); // 递增位次
}
}
package org.example.mapreduce;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class SortDriver {
public static void main(String[] args) throws Exception {
// 本地输入文件目录和输出文件路径
String localInputDir = "src/main/java/org/example/mapreduce/inputFile";
String localOutputFile = "output_local/result2.txt";
// HDFS输入和输出路径
String hdfsInputDir = "/user/hadoop/input/";
String hdfsOutputDir = "/user/hadoop/output/";
// 配置Hadoop文件系统
Configuration conf = new Configuration();
System.setProperty("HADOOP_USER_NAME","hadoop");
conf.set("fs.defaultFS", "hdfs://192.168.70.143:8020");
FileSystem fs = FileSystem.get(conf);
// 1. 上传本地文件到HDFS
uploadDirectoryToHDFS(fs, localInputDir, hdfsInputDir);
// 2. 设置MapReduce作业
Job job = Job.getInstance(conf, "Sort Numbers");
job.setJarByClass(SortDriver.class);
job.setMapperClass(SortMapper.class);
job.setReducerClass(SortReducer.class);
job.setMapOutputKeyClass(IntWritable.class);
job.setMapOutputValueClass(IntWritable.class);
job.setOutputKeyClass(IntWritable.class);
job.setOutputValueClass(IntWritable.class);
// 设置输入和输出路径
FileInputFormat.addInputPath(job, new Path(hdfsInputDir));
FileOutputFormat.setOutputPath(job, new Path(hdfsOutputDir));
// 3. 提交任务并等待完成
boolean success = job.waitForCompletion(true);
if (!success) {
System.err.println("Job failed!");
System.exit(1);
}
// 4. 下载输出文件到本地
downloadFromHDFS(fs, hdfsOutputDir + "/part-r-00000", localOutputFile);
System.out.println("Job completed successfully. Output file is saved to: " + localOutputFile);
// 5. 删除HDFS中的临时目录
fs.delete(new Path(hdfsInputDir), true);
fs.delete(new Path(hdfsOutputDir), true);
}
// 上传本地目录中的所有文件到HDFS
private static void uploadDirectoryToHDFS(FileSystem fs, String localDirPath, String hdfsDirPath) throws IOException {
File localDir = new File(localDirPath);
if (!localDir.isDirectory()) {
throw new IOException(localDirPath + " is not a valid directory.");
}
for (File file : localDir.listFiles()) {
if (file.isFile()) {
Path src = new Path(file.getAbsolutePath());
Path dest = new Path(hdfsDirPath + file.getName());
fs.copyFromLocalFile(false, true, src, dest);
System.out.println("Uploaded: " + src + " to " + dest);
}
}
}
// 从HDFS下载文件到本地
private static void downloadFromHDFS(FileSystem fs, String hdfsPath, String localPath) throws IOException {
Path src = new Path(hdfsPath);
File localFile = new File(localPath);
localFile.getParentFile().mkdirs(); // 确保本地目录存在
try (
FSDataInputStream inputStream = fs.open(src);
FileOutputStream outputStream = new FileOutputStream(localFile)
) {
byte[] buffer = new byte[4096]; // 缓冲区大小
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, bytesRead);
}
}
System.out.println("Downloaded: " + hdfsPath + " to " + localPath);
}
}
(三)对给定的表格进行信息挖掘
下面给出一个child-parent的表格,要求挖掘其中的父子辈关系,给出祖孙辈关系的表格。
输入文件内容如下:
child parent
Steven Lucy
Steven Jack
Jone Lucy
Jone Jack
Lucy Mary
Lucy Frank
Jack Alice
Jack Jesse
David Alice
David Jesse
Philip David
Philip Alma
Mark David
Mark Alma
输出文件内容如下:
grandchild grandparent
Steven Alice
Steven Jesse
Jone Alice
Jone Jesse
Steven Mary
Steven Frank
Jone Mary
Jone Frank
Philip Alice
Philip Jesse
Mark Alice
Mark Jesse
package org.example.mapreduce;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
public class GrandchildMapper extends Mapper<Object, Text, Text, Text> {
private Text keyOut = new Text();
private Text valueOut = new Text();
@Override
protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString().trim();
// 跳过表头
if (line.startsWith("child")) {
return;
}
// 分割行,提取child和parent
String[] parts = line.split("\\s+");
if (parts.length == 2) {
String child = parts[0];
String parent = parts[1];
// 输出child -> parent
keyOut.set(parent);
valueOut.set("child:" + child);
context.write(keyOut, valueOut);
// 输出parent -> grandparent
valueOut.set("parent:" + parent);
context.write(keyOut, valueOut);
}
}
}
package org.example.mapreduce;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class GrandchildReducer extends Reducer<Text, Text, Text, Text> {
private Text grandchild = new Text();
private Text grandparent = new Text();
@Override
protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
// 存储child和grandparent
List<String> children = new ArrayList<>();
List<String> grandparents = new ArrayList<>();
for (Text value : values) {
String val = value.toString();
if (val.startsWith("child:")) {
children.add(val.substring(6));
} else if (val.startsWith("parent:")) {
grandparents.add(val.substring(7));
}
}
// 组合child和grandparent输出祖孙关系
for (String child : children) {
for (String gp : grandparents) {
grandchild.set(child);
grandparent.set(gp);
context.write(grandchild, grandparent);
}
}
}
}
package org.example.mapreduce;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class GrandchildDriver {
public static void main(String[] args) throws Exception {
// 本地输入文件和输出路径
String localInputFile = "src/main/java/org/example/mapreduce/inputFile2/relations.txt";
String localOutputFile = "output_local/result3.txt";
// HDFS 输入输出路径
String hdfsInputPath = "/user/hadoop/input/relations.txt.txt";
String hdfsOutputDir = "/user/hadoop/output/";
// 配置Hadoop文件系统
Configuration conf = new Configuration();
System.setProperty("HADOOP_USER_NAME","hadoop");
conf.set("fs.defaultFS", "hdfs://192.168.70.143:8020");
FileSystem fs = FileSystem.get(conf);
// 1. 上传本地文件到 HDFS
uploadToHDFS(fs, localInputFile, hdfsInputPath);
// 2. 设置 MapReduce 作业
Job job = Job.getInstance(conf, "Grandchild Relationships");
job.setJarByClass(GrandchildDriver.class);
job.setMapperClass(GrandchildMapper.class);
job.setReducerClass(GrandchildReducer.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Text.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job, new Path(hdfsInputPath));
FileOutputFormat.setOutputPath(job, new Path(hdfsOutputDir));
// 3. 提交任务并等待完成
boolean success = job.waitForCompletion(true);
if (!success) {
System.err.println("Job failed!");
System.exit(1);
}
// 4. 下载结果文件到本地
downloadFromHDFS(fs, hdfsOutputDir + "part-r-00000", localOutputFile);
System.out.println("Job completed successfully. Output file is saved to: " + localOutputFile);
// 5. 删除 HDFS 临时目录
fs.delete(new Path(hdfsInputPath), true);
fs.delete(new Path(hdfsOutputDir), true);
}
// 上传本地文件到 HDFS
private static void uploadToHDFS(FileSystem fs, String localPath, String hdfsPath) throws IOException {
Path src = new Path(localPath);
Path dest = new Path(hdfsPath);
fs.copyFromLocalFile(false, true, src, dest);
System.out.println("Uploaded: " + src + " to " + dest);
}
// 从 HDFS 下载文件到本地
private static void downloadFromHDFS(FileSystem fs, String hdfsPath, String localPath) throws IOException {
Path src = new Path(hdfsPath);
File localFile = new File(localPath);
localFile.getParentFile().mkdirs(); // 确保本地目录存在
try (
FSDataInputStream inputStream = fs.open(src);
FileOutputStream outputStream = new FileOutputStream(localFile)
) {
byte[] buffer = new byte[4096]; // 缓冲区大小
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, bytesRead);
}
}
System.out.println("Downloaded: " + hdfsPath + " to " + localPath);
}
}

浙公网安备 33010602011771号