期末复习-Hadoop综合复习

打印 上一主题 下一主题

主题 833|帖子 833|积分 2499

说明

以下内容仅供参考,提到不代表考到,请结合实际情况本身复习
目录
说明
一、题型及分值
二、综合案例题-摆设Hadoop集群 或 摆设Hadoop HA集群
三、名称表明(8选5)
1.什么是大数据
2.大数据的5V特征
3.什么是SSH
4.HDFS(p32)
5.名称节点
6.数据节点
7.元数据
8.倒排索引
9.单点故障
10.高可用
11.数据堆栈
四、简答题
1、简述Hadoop的优点及其含义
2.简述独立模式、伪分布式模式和完全分布式模式摆设Hadoop的区别
3.简述HDFS的健壮性
4.简述YARN根本架构的组成部分及其作用
5.简述不同范例ZNode的区别
6.简述Hadoop高可用集群初次启动时的步骤
7.简述Hive中分区和桶的作用
五、Hive代码题
题目: 电商订单分析
答案
六、HDFS代码题
课本资料
相关题目
题目 1: 创建目录并上传文件
题目 2: 检察文件信息
题目 3: 数据移动与复制
题目 4: 删除操作
题目 5: 文件权限设置
题目 6: 文件备份与验证
七、MapReduce编程
题目 1: 单词计数 (Word Count)
题目 2: 最大值求解 (Max Value Finder)
 题目 3: 匀称值盘算 (Average Calculation)
题目 4: Top K 单词统计
思路
题目 5: 日志分析
 题目 6: 用户购买分析
题目 7: 倒排索引 (Inverted Index)
 题目 8: 用户商品共现分析
 题目 9: 数据去重
题目 10: 分组统计 (Group By)


一、题型及分值

1.综合案例题(35分)
2.名词表明(每个3分,共15分)
3.简答题(每题6分,共30分)
4.编程题(共3题,共20分)

二、综合案例题-摆设Hadoop集群 或 摆设Hadoop HA集群

这部分内容发起观看课本
  1. tar -zxvf jdk-8u... -C /export/...
复制代码
  1. 在Linux系统中,tar命令用于打包和解包文件。以下是tar命令中 -zxvf 和 -C 选项的含义:
  2. -z:这个选项表示同时通过gzip进行压缩或解压缩。如果.tar文件实际上是一个.tar.gz或.tgz文件,这个选项是必要的。
  3. -x:这个选项代表解包(extract)一个.tar文件。
  4. -v:这个选项用于在处理文件时显示详细信息(verbose),它会列出正在处理的文件,这样用户可以看到解压的进度和具体内容。
  5. -f:这个选项用于指定要处理的文件名。在tar命令中,-f通常是最后一个选项,并且后面直接跟着要操作的文件名。
  6. 所以,-zxvf组合起来就是告诉tar命令:解压缩一个用gzip压缩的.tar.gz文件,并在处理过程中显示详细信息。
  7. -C:这个选项告诉tar命令在指定的目录中解包文件。在上面的命令中,-C /export/…表示将文件解压到/export/…这个目录下。
  8. 综上所述,tar -zxvf jdk-8u... -C /export/…命令的作用是:以详细方式解压名为jdk-8u...的gzip压缩的tar文件,并将其内容解压到/export/…目录中。注意,jdk-8u...是文件名的占位符,你需要替换为实际的文件名。
复制代码
  1. # 验证Hadoop是否安装成功
  2. bin/hadoop version
复制代码
  1. # 启动Hadoop
  2. start-dfs.sh
  3. # 启动yarn
  4. start-yarn.sh
  5. # 查看hadoop运行状态
  6. jps
复制代码
三、名称表明(8选5)

1.什么是大数据

大数据指的是海量数据;具有海量、流转快、数据范例丰富及价值密度低等特点
2.大数据的5V特征

大数据的特征包括大量(Volume)、真实(Veracity)、多样(Variety)、低价值密度(Value)和高速(Velocity)
3.什么是SSH

SSH是一种网络协议,主要用于在不安全网络上提供安全的长途登录和其他安全网络服务。它可以或许加密网络连接,确保在客户端和服务器之间传输的数据不会容易被窃取或篡改。
4.HDFS(p32)

HDFS是Hadoop Distributed File System的缩写,中文称为Hadoop分布式文件系统,专为大规模数据集的处理而计划,主要用于存储和管理海量数据文件。
5.名称节点

NameNode是HDFS集群的名称节点,通常称为主节点。假如NameNode由于故障原因而无法利用,那么用户就无法访问HDFS。也就是说,NameNode作为HDFS的主节点,起着至关重要的部分
6.数据节点

DataNode是HDFS集群中的数据节点,通常称为从节点,其主要功能如下:


  • 存储Block
  • 根据NameNode的指令对Block举行创建、复制、删除等操作
  • 定期向NameNode报告自身存储的Block列表及健康状态
  • 负责为客户端发起的读写请求提供服务
7.元数据

MetaData用于记载HDFS文件系统的相关信息,这些信息称为元数据,元数据的内容包括文件系统的目录结构、文件名、文件路径、文件大小、文件副本数、文件与Block的映射关系,以及Block与DataNode的映射关系等信息
8.倒排索引

倒排索引是文档检索系统中最常用的数据结构,被广泛应用于全文搜索引擎。倒排索引主要用来存储某个单词或词组在一组文档中的存储位置的映射,提供了可以根据内容查找文档的方式,而不是根据文档确定内容,因此称为倒排索引。
9.单点故障

在HDFS集群中,NameNode是主节点,它的运行状态决定着HDFS集群是否可用。然而在Hadoop计划之初,HDFS集群只能存在一个NameNode节点,这种计划的缺点是NameNode节点一旦发生故障,就会导致HDFS集群不可用,这就是所谓的单点故障问题
10.高可用

Hadoop通过在HDFS集群中配置多个NameNode(一个Active,多个Standby)来确保系统连续运行,当Active NameNode故障时,自动选举新的Active NameNode,防止单点故障。
11.数据堆栈

数据堆栈是一个面向主题、集成的、相对稳固和反映汗青变化的数据集合,用于企业或组织的决策分析。

四、简答题

有的来自于书籍,有的来自于AI(因为书籍内容过多)
1、简述Hadoop的优点及其含义

  1.     (1)低成本,可用多台廉价机组建集群,分布式处理大数据,降低成本。
  2.         (2)高可靠性,自动保存数据副本,避免数据丢失。
  3.     (3)高容错性,自动检测并应对故障,通过任务转移,防止任务失败。
  4.     (4)高效率,Hadoop可高效的执行并行计算,且在各个计算机中动态地移动计算。
  5.     (5)高扩展性,可随时添加更多的计算机,增加集群存储,计算能力。
复制代码
2.简述独立模式、伪分布式模式和完全分布式模式摆设Hadoop的区别

  1.   (1)独立模式:本地独立模式不进行任何配置,是Hadoop的默认工作模式,所有组件都在同一台机器运行,适用于学习和体验。
  2.   (2)伪分布模式:也是在一台单机上运行,通过单节点模拟分布式,但部署的Hadoop集群是一个伪分布式系统,适合本地开发和验证。
  3.   (3)完全分布模式:是一种在多台计算机JVM进程中运行Hadoop集群的工作模式,所有组件分布在多台机器上,部署的集群是完全分布式系统,适用于生产环境。
复制代码
3.简述HDFS的健壮性

其健壮性可表现为:在HDFS出现故障的情况下可靠的存储数据,其运用了心跳机制、副本机制、数据完备性校验、安全模式和快照 5 种计谋保证了数据存储的可靠性
4.简述YARN根本架构的组成部分及其作用

YARN 根本架构由 ResourceManager、ApplicationMaster、NodeManager 和 Container 组成,其中,ResourceManager 为全局资源管理器,负责整个系统的资源管理和分配;ApplicationMaster每个应用步伐特有的,负责单个应用步伐的管理;NodeManager 负责在节点上启动和管理Container(容器);Container 封装了每个应用步伐利用的资源。
5.简述不同范例ZNode的区别

ZooKeeper中的ZNode范例主要有以下区别:

  • 持久节点:除非手动删除,否则一直存在。
  • 临时节点:随客户端会话结束而自动删除,不能有子节点。
  • 顺序节点:在持久或临时节点基础上,创建时带唯一递增序号,用于记载创建顺序。
6.简述Hadoop高可用集群初次启动时的步骤

1.启动JournalNode
  1. hdfs -- daemon start journalnode
复制代码
2.格式化HDFS文件系统
  1. hdfs namenode -format
复制代码
3.同步NameNode
  1. scp -r /export/data/hadoop/namenode/ hadoop2:/export/data/hadoop/
复制代码
4.格式化ZKFC
  1. hdfs zkfc -formatZK
复制代码
5.启动HDFS
  1. start-dfs.sh
复制代码
6.启动YARN
  1. start-yarn.sh
复制代码
7.简述Hive中分区和桶的作用

分区:将表数据按规则分别存储在不同目录,减少全表扫描,提高查询效率。 桶:按规则将数据匀称分布在不同文件中,制止数据倾斜,优化查询性能。
五、Hive代码题

  1. Hive实践作业三
  2. 7.5 数据库操作
  3. 7.6 表操作
  4. 1.在hadoop1中执行start-dfs.sh和start-yarn.sh分别启动hdfs和yarn,
  5. 保证hadoop完全分布式集群正常启动,
  6. hadoop1 jps NameNode ResourceManager
  7. hadoop2 jps NodeManager DataNode SecondaryNameNode
  8. hadoop3 jps NodeManager DataNode
  9. 2.在hadoop3中执行systemctl status mysqld验证mysql80正常启动
  10. 3.在hadoop3中启动MetaStore服务,hive --service metastore
  11. 4.hadoop3复制会话,启动HiveServer2服务,hive --service hiveserver2
  12. 5.hadoop3再次复制会话,jps 多了两个RunJar进程,元数据存储系统和HiveServer2正常启动
  13. 6.在hadoop2中,执行 hive 登录
  14. 7.hadoop2复制会话,执行 beeline -u jdbc:hive2://hadoop3:10000 -n root 登录
  15. 8.在登录的hive中,输入:show databases;
  16. 9.数据库操作
  17. 创建数据库 create database homework;
  18. 查看数据库 describe homework;
  19. 切换数据库 use homework;
  20. 10.表操作
  21. complex表的创建
  22. create table complex(
  23. col1 array<int>,
  24. col2 map<int,string>,
  25. col3 struct<a:string,b:int,c:double>,
  26. col4 string,
  27. col5 int
  28. );
  29. complex表的查看
  30. desc complex;
  31. user_p分区表的创建
  32. create table user_p (id int, name string)
  33. partitioned by (gender string)
  34. row format delimited fields terminated by ',';
  35. user_p分区表的查看
  36. desc user_p;
  37. array_test内部表的创建
  38. create table array_test(
  39. name string,
  40. score array<int>
  41. )
  42. row format delimited fields terminated by '@'
  43. collection items terminated by ',';
  44. array_test内部表导入数据
  45. zhangshan@89,88,97,80
  46. lisi@90,95,99,97
  47. wangwu@90,77,88,79
  48. zhaoliu@91,79,98,89
  49. 文本文件array_test.txt需要先创建,在hadoop3上哦
  50. load data local inpath '/root/array_test.txt' into table homework.array_test;
  51. array_test内部表查询数据
  52. select * from homework.array_test;
  53. map_test内部表的创建
  54. create table map_test(
  55. name string,
  56. score map<string,int>
  57. )
  58. row format delimited fields terminated by '@'
  59. collection items terminated by ','
  60. map keys terminated by ':';
  61. map_test内部表导入数据
  62. zhangshan@math:90,english:89,java:88,hive:80
  63. lisi@math:98,english:79,java:96,hive:92
  64. wangwu@math:88,english:86,java:89,hive:88
  65. zhaoliu@math:89,english:78,java:79,hive:77
  66. 文本文件map_test.txt需要先创建,在hadoop3上哦
  67. load data local inpath '/root/map_test.txt' into table homework.map_test;
  68. map_test内部表查询数据
  69. select * from homework.map_test;
  70. select name from homework.map_test;
  71. select score from homework.map_test;
复制代码
题目: 电商订单分析

某电商公司必要构建订单管理系统,并在 Hive 中完成以下任务:
数据描述
订单数据由以下信息组成:

  • order_id (订单ID, INT)
  • customer_id (客户ID, INT)
  • order_date (订单日期, STRING,格式:yyyy-MM-dd)
  • order_items (订单商品,ARRAY<STRUCT<item_id: INT, item_name: STRING, quantity: INT, price: FLOAT>>)
  • order_details (订单详情,MAP<STRING, STRING>,包含键值对如 payment_method -> credit_card, delivery_status -> delivered)
任务要求:
任务 1: 内部表创建
创建一个内部表 orders_internal,用于存储上述订单数据。
任务 2: 外部表创建
创建一个外部表 orders_external,数据存储在 HDFS 的 /data/orders_external/ 目录下。
任务 3: 分区表创建
创建一个按 order_date 分区的表 orders_partitioned,优化按日期范围查询的性能。
任务 4: 数据插入
为三个表分别插入以下样例数据:
  1. 订单1:
  2.   order_id: 101, customer_id: 1, order_date: '2024-12-01'
  3.   order_items: [
  4.     {item_id: 201, item_name: 'Laptop', quantity: 1, price: 1000.0},
  5.     {item_id: 202, item_name: 'Mouse', quantity: 2, price: 25.0}
  6.   ]
  7.   order_details: {'payment_method': 'credit_card', 'delivery_status': 'delivered'}
  8. 订单2:
  9.   order_id: 102, customer_id: 2, order_date: '2024-12-02'
  10.   order_items: [
  11.     {item_id: 203, item_name: 'Keyboard', quantity: 1, price: 50.0}
  12.   ]
  13.   order_details: {'payment_method': 'paypal', 'delivery_status': 'shipped'}
复制代码
任务 5: 查询操作

  • 查询所有已完成(delivery_status = delivered)订单的客户ID及商品明细。
  • 查询每个客户的总消费金额。
答案

任务 1: 内部表创建
  1. CREATE TABLE orders_internal (
  2.     order_id INT,
  3.     customer_id INT,
  4.     order_date STRING,
  5.     order_items ARRAY<STRUCT<item_id: INT, item_name: STRING, quantity: INT, price: FLOAT>>,
  6.     order_details MAP<STRING, STRING>
  7. )
  8. ROW FORMAT DELIMITED
  9. FIELDS TERMINATED BY '\t'
  10. COLLECTION ITEMS TERMINATED BY ','
  11. MAP KEYS TERMINATED BY ':';
复制代码
任务 2: 外部表创建
  1. CREATE EXTERNAL TABLE orders_external (
  2.     order_id INT,
  3.     customer_id INT,
  4.     order_date STRING,
  5.     order_items ARRAY<STRUCT<item_id: INT, item_name: STRING, quantity: INT, price: FLOAT>>,
  6.     order_details MAP<STRING, STRING>
  7. )
  8. STORED AS TEXTFILE
  9. LOCATION '/data/orders_external/';
复制代码
任务 3: 分区表创建
  1. CREATE TABLE orders_partitioned (
  2.     order_id INT,
  3.     customer_id INT,
  4.     order_items ARRAY<STRUCT<item_id: INT, item_name: STRING, quantity: INT, price: FLOAT>>,
  5.     order_details MAP<STRING, STRING>
  6. )
  7. PARTITIONED BY (order_date STRING)
  8. ROW FORMAT DELIMITED
  9. FIELDS TERMINATED BY '\t'
  10. COLLECTION ITEMS TERMINATED BY ','
  11. MAP KEYS TERMINATED BY ':';
复制代码
任务 4: 数据插入
插入内部表
  1. INSERT INTO TABLE orders_internal VALUES
  2. (101, 1, '2024-12-01',
  3.     ARRAY(
  4.         NAMED_STRUCT('item_id', 201, 'item_name', 'Laptop', 'quantity', 1, 'price', 1000.0),
  5.         NAMED_STRUCT('item_id', 202, 'item_name', 'Mouse', 'quantity', 2, 'price', 25.0)
  6.     ),
  7.     MAP('payment_method', 'credit_card', 'delivery_status', 'delivered')
  8. ),
  9. (102, 2, '2024-12-02',
  10.     ARRAY(
  11.         NAMED_STRUCT('item_id', 203, 'item_name', 'Keyboard', 'quantity', 1, 'price', 50.0)
  12.     ),
  13.     MAP('payment_method', 'paypal', 'delivery_status', 'shipped')
  14. );
复制代码
插入外部表: 将数据手动存储在 /data/orders_external/,格式如下:
  1. 101    1    2024-12-01    [{"item_id":201,"item_name":"Laptop","quantity":1,"price":1000.0},{"item_id":202,"item_name":"Mouse","quantity":2,"price":25.0}]    {"payment_method":"credit_card","delivery_status":"delivered"}
  2. 102    2    2024-12-02    [{"item_id":203,"item_name":"Keyboard","quantity":1,"price":50.0}]    {"payment_method":"paypal","delivery_status":"shipped"}
复制代码
加载数据后,直接查询外部表。
插入分区表
  1. INSERT INTO TABLE orders_partitioned PARTITION(order_date='2024-12-01') VALUES
  2. (101, 1,
  3.     ARRAY(
  4.         NAMED_STRUCT('item_id', 201, 'item_name', 'Laptop', 'quantity', 1, 'price', 1000.0),
  5.         NAMED_STRUCT('item_id', 202, 'item_name', 'Mouse', 'quantity', 2, 'price', 25.0)
  6.     ),
  7.     MAP('payment_method', 'credit_card', 'delivery_status', 'delivered')
  8. );
  9. INSERT INTO TABLE orders_partitioned PARTITION(order_date='2024-12-02') VALUES
  10. (102, 2,
  11.     ARRAY(
  12.         NAMED_STRUCT('item_id', 203, 'item_name', 'Keyboard', 'quantity', 1, 'price', 50.0)
  13.     ),
  14.     MAP('payment_method', 'paypal', 'delivery_status', 'shipped')
  15. );
复制代码
任务 5: 查询操作
1. 查询所有已完成(delivery_status = delivered)订单的客户ID及商品明细
  1. SELECT
  2.     customer_id,
  3.     order_items
  4. FROM
  5.     orders_internal
  6. WHERE
  7.     order_details['delivery_status'] = 'delivered';
复制代码
2. 查询每个客户的总消费金额
  1. SELECT
  2.     customer_id,
  3.     SUM(total_price) AS total_spent
  4. FROM (
  5.     SELECT
  6.         customer_id,
  7.         item.quantity * item.price AS total_price
  8.     FROM
  9.         orders_internal
  10.         LATERAL VIEW EXPLODE(order_items) exploded_items AS item
  11. ) t
  12. GROUP BY
  13.     customer_id;
复制代码
六、HDFS代码题

课本资料

dfs常用的子命令选项
子命令选项功能描述-ls检察指定目录信息-du检察指定目录下每个文件和子目录的大小,子目录也可以看作单独的目录,因为它也可 以存在于目录-mv移动到指定文件或目录-cp复制指定文件或目录-rm删除指定文件或目录-put将本地文件系统中的指定文件传到 HDFS 指定目录-cat检察指定文件的内容-help检察资助文档-mkdir创建目录-get将 HDFS 的指定文件下载到本地文件系统
  1. 1.查看目录 /data的信息
  2. hdfs dfs -ls -S /data
  3. -S 按照由大到小的顺序显示指定目录的内容
  4. 根据文件内容大小,按照由小到大的顺序显示目录 /data的内容,并将默认的文件大小格式化为便于查看的格式进行显示
  5. hdfs dfs -ls -r -h /data
  6. -r 根据文件大小按照由小到大的顺序显示目录
  7. -h 将默认文件大小(字节数)格式化为便于查看的格式进行显示
  8. 递归显示目录/data及其子目录的信息,信息中仅显示文件和子目录的路径
  9. hdfs dfs -ls -R -C /data
  10. -R 递归显示目录/data及其子目录的信息
  11. -C 信息中仅显示文件和子目录的路径
  12. 2.在HDFS的目录/data中创建子目录/dataChild1。并在子目录/dataChild1中创建子目录/dataChild2
  13. hdfs dfs -mkdir -p /data/dataChild1/dataChild2
  14. 3.查看/data中每个文件和子目录的大小,并将默认的文件和子目录大小格式化为便于查看的格式进行显示
  15. hdfs dfs -du -h /data
  16. 4.将目录/data中的子目录/dataChild1 移动到目录/data/dataChild中
  17. hdfs dfs -mv /dataChild1 /data/dataChild
  18. 将目录/data中的文件dataA 重命名为dataA_New
  19. hdfs dfs -mv /data/dataA /data/dataA_New
  20. 5.将目录/data下的文件dataA_New 和 dataB复制到目录/data/dataChild
  21. hdfs dfs -cp /data/dataA_New /data/dataB_New /data/dataChild
  22. 将目录/data下的文件 dataA_New复制到子目录/dataChild,并将其重命名为dataA
  23. hdfs dfs -cp /data/dataA_New /data/dataChild/dataA
  24. 6.删除目录/data的子目录/dataChild
  25. hdfs dfs -rm -r /data/dataChild
  26. 7.将本地文件系统中/export/data目录下文件a.txt 和 b.txt上传到HDFS的目录/data
  27. hdfs dfs -put /export/data/a.txt /export/data/b.txt /data
  28. 8.查看目录/data中的文件a.txt的内容
  29. hdfs dfs -cat /data/a.txt
  30. 9.将HDFS中目录/data中的文件a.txt和b.txt 下载到本地文件系统/opt目录下
  31. hdfs dfs -get /data/a.txt /data/b.txt /opt
复制代码

相关题目

题目 1: 创建目录并上传文件

描述: 假设你在 HDFS 的根目录下,必要完成以下操作:

  • 在 HDFS 中创建一个名为 /user/yourname/data 的目录。
  • 将本地目录 /local/data/input.txt 中的文件上传到刚创建的 HDFS 目录中。
要求: 编写 Shell 命令完成以上任务。

题目 2: 检察文件信息

描述: 假设 HDFS 中已经存在目录 /user/yourname/data/input.txt,必要完成以下操作:

  • 检察该文件的具体信息(包括文件权限、大小等)。
  • 表现该文件的内容。
要求: 写出相应的 HDFS Shell 命令。


题目 3: 数据移动与复制

描述

  • 将文件 /user/yourname/data/input.txt 移动到 HDFS 中的 /user/yourname/archive/ 目录下。
  • 将文件 /user/yourname/archive/input.txt 复制回 /user/yourname/data/ 目录。
要求: 提供具体的 HDFS Shell 命令。

题目 4: 删除操作

描述: 删除 HDFS 中的 /user/yourname/data 目录及其内容,并验证该目录是否被乐成删除。
要求: 写出执行以上操作的 Shell 命令。


题目 5: 文件权限设置

描述: 假设 /user/yourname/data/input.txt 文件必要满意以下权限要求:

  • 文件所有者可以读写;
  • 文件所在组成员只能读取;
  • 其他用户无权限。
要求: 提供修改文件权限的 HDFS Shell 命令。

题目 6: 文件备份与验证

描述

  • 将 HDFS 中的 /user/yourname/data/input.txt 备份到 /user/yourname/backup/input.txt。
  • 验证备份文件与原文件的内容是否同等。
要求: 写出完备的 Shell 命令。


七、MapReduce编程

题目 1: 单词计数 (Word Count)


  1. import org.apache.hadoop.conf.Configuration;
  2. import org.apache.hadoop.fs.Path;
  3. import org.apache.hadoop.io.IntWritable;
  4. import org.apache.hadoop.io.Text;
  5. import org.apache.hadoop.mapreduce.Job;
  6. import org.apache.hadoop.mapreduce.Mapper;
  7. import org.apache.hadoop.mapreduce.Reducer;
  8. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
  9. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
  10. import java.io.IOException;
  11. public class WordCount {
  12.     public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> {
  13.         private final static IntWritable one = new IntWritable(1);
  14.         private Text word = new Text();
  15.         public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
  16.             String[] tokens = value.toString().split("\\s+");
  17.             for (String token : tokens) {
  18.                 word.set(token);
  19.                 context.write(word, one);
  20.             }
  21.         }
  22.     }
  23.     public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
  24.         private IntWritable result = new IntWritable();
  25.         public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
  26.             int sum = 0;
  27.             for (IntWritable val : values) {
  28.                 sum += val.get();
  29.             }
  30.             result.set(sum);
  31.             context.write(key, result);
  32.         }
  33.     }
  34.     public static void main(String[] args) throws Exception {
  35.         Configuration conf = new Configuration();
  36.         Job job = Job.getInstance(conf, "word count");
  37.         job.setJarByClass(WordCount.class);
  38.         job.setMapperClass(TokenizerMapper.class);
  39.         job.setCombinerClass(IntSumReducer.class);
  40.         job.setReducerClass(IntSumReducer.class);
  41.         job.setOutputKeyClass(Text.class);
  42.         job.setOutputValueClass(IntWritable.class);
  43.         FileInputFormat.addInputPath(job, new Path(args[0]));
  44.         FileOutputFormat.setOutputPath(job, new Path(args[1]));
  45.         System.exit(job.waitForCompletion(true) ? 0 : 1);
  46.     }
  47. }
复制代码

题目 2: 最大值求解 (Max Value Finder)


  1. import org.apache.hadoop.conf.Configuration;
  2. import org.apache.hadoop.fs.Path;
  3. import org.apache.hadoop.io.IntWritable;
  4. import org.apache.hadoop.io.Text;
  5. import org.apache.hadoop.mapreduce.Job;
  6. import org.apache.hadoop.mapreduce.Mapper;
  7. import org.apache.hadoop.mapreduce.Reducer;
  8. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
  9. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
  10. import java.io.IOException;
  11. public class MaxValue {
  12.     public static class MaxMapper extends Mapper<Object, Text, Text, IntWritable> {
  13.         private final static Text keyOut = new Text("Max");
  14.         public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
  15.             int num = Integer.parseInt(value.toString());
  16.             context.write(keyOut, new IntWritable(num));
  17.         }
  18.     }
  19.     public static class MaxReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
  20.         public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
  21.             int max = Integer.MIN_VALUE;
  22.             for (IntWritable val : values) {
  23.                 max = Math.max(max, val.get());
  24.             }
  25.             context.write(key, new IntWritable(max));
  26.         }
  27.     }
  28.     public static void main(String[] args) throws Exception {
  29.         Configuration conf = new Configuration();
  30.         Job job = Job.getInstance(conf, "max value");
  31.         job.setJarByClass(MaxValue.class);
  32.         job.setMapperClass(MaxMapper.class);
  33.         job.setReducerClass(MaxReducer.class);
  34.         job.setOutputKeyClass(Text.class);
  35.         job.setOutputValueClass(IntWritable.class);
  36.         FileInputFormat.addInputPath(job, new Path(args[0]));
  37.         FileOutputFormat.setOutputPath(job, new Path(args[1]));
  38.         System.exit(job.waitForCompletion(true) ? 0 : 1);
  39.     }
  40. }
复制代码
 题目 3: 匀称值盘算 (Average Calculation)


  1. import org.apache.hadoop.conf.Configuration;
  2. import org.apache.hadoop.fs.Path;
  3. import org.apache.hadoop.io.IntWritable;
  4. import org.apache.hadoop.io.Text;
  5. import org.apache.hadoop.mapreduce.Job;
  6. import org.apache.hadoop.mapreduce.Mapper;
  7. import org.apache.hadoop.mapreduce.Reducer;
  8. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
  9. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
  10. import java.io.IOException;
  11. public class AverageCalculation {
  12.     public static class AvgMapper extends Mapper<Object, Text, Text, IntWritable> {
  13.         private final static Text keyOut = new Text("Average");
  14.         public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
  15.             int num = Integer.parseInt(value.toString());
  16.             context.write(keyOut, new IntWritable(num));
  17.         }
  18.     }
  19.     public static class AvgReducer extends Reducer<Text, IntWritable, Text, Text> {
  20.         public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
  21.             int sum = 0, count = 0;
  22.             for (IntWritable val : values) {
  23.                 sum += val.get();
  24.                 count++;
  25.             }
  26.             double average = (double) sum / count;
  27.             context.write(key, new Text(String.format("%.2f", average)));
  28.         }
  29.     }
  30.     public static void main(String[] args) throws Exception {
  31.         Configuration conf = new Configuration();
  32.         Job job = Job.getInstance(conf, "average calculation");
  33.         job.setJarByClass(AverageCalculation.class);
  34.         job.setMapperClass(AvgMapper.class);
  35.         job.setReducerClass(AvgReducer.class);
  36.         job.setOutputKeyClass(Text.class);
  37.         job.setOutputValueClass(IntWritable.class);
  38.         FileInputFormat.addInputPath(job, new Path(args[0]));
  39.         FileOutputFormat.setOutputPath(job, new Path(args[1]));
  40.         System.exit(job.waitForCompletion(true) ? 0 : 1);
  41.     }
  42. }
复制代码
题目 4: Top K 单词统计


答案:通过两阶段 MapReduce 实现:第一阶段统计单词频率,第二阶段从中找出频率最高的 K 个单词。
第一阶段:统计单词频率
这部分代码与常规单词计数雷同。
  1. import org.apache.hadoop.conf.Configuration;
  2. import org.apache.hadoop.fs.Path;
  3. import org.apache.hadoop.io.IntWritable;
  4. import org.apache.hadoop.io.Text;
  5. import org.apache.hadoop.mapreduce.Job;
  6. import org.apache.hadoop.mapreduce.Mapper;
  7. import org.apache.hadoop.mapreduce.Reducer;
  8. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
  9. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
  10. import java.io.IOException;
  11. public class WordFrequency {
  12.     public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> {
  13.         private final static IntWritable one = new IntWritable(1);
  14.         private Text word = new Text();
  15.         public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
  16.             String[] tokens = value.toString().split("\\s+");
  17.             for (String token : tokens) {
  18.                 word.set(token);
  19.                 context.write(word, one);
  20.             }
  21.         }
  22.     }
  23.     public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
  24.         private IntWritable result = new IntWritable();
  25.         public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
  26.             int sum = 0;
  27.             for (IntWritable val : values) {
  28.                 sum += val.get();
  29.             }
  30.             result.set(sum);
  31.             context.write(key, result);
  32.         }
  33.     }
  34.     public static void main(String[] args) throws Exception {
  35.         Configuration conf = new Configuration();
  36.         Job job = Job.getInstance(conf, "word frequency");
  37.         job.setJarByClass(WordFrequency.class);
  38.         job.setMapperClass(TokenizerMapper.class);
  39.         job.setReducerClass(IntSumReducer.class);
  40.         job.setOutputKeyClass(Text.class);
  41.         job.setOutputValueClass(IntWritable.class);
  42.         FileInputFormat.addInputPath(job, new Path(args[0]));
  43.         FileOutputFormat.setOutputPath(job, new Path(args[1]));
  44.         System.exit(job.waitForCompletion(true) ? 0 : 1);
  45.     }
  46. }
复制代码


第二阶段:提取 Top K
思路

第二阶段通过输入第一阶段的输出结果,将频率和单词对交换,按频率降序排序,选出频率最高的 K 个单词
  1. import org.apache.hadoop.conf.Configuration;
  2. import org.apache.hadoop.fs.Path;
  3. import org.apache.hadoop.io.IntWritable;
  4. import org.apache.hadoop.io.Text;
  5. import org.apache.hadoop.mapreduce.Job;
  6. import org.apache.hadoop.mapreduce.Mapper;
  7. import org.apache.hadoop.mapreduce.Reducer;
  8. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
  9. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
  10. import java.io.IOException;
  11. import java.util.TreeMap;
  12. public class TopKWords {
  13.     public static class SwapMapper extends Mapper<Object, Text, IntWritable, Text> {
  14.         private IntWritable frequency = new IntWritable();
  15.         private Text word = new Text();
  16.         public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
  17.             String[] parts = value.toString().split("\\s+");
  18.             if (parts.length == 2) {
  19.                 word.set(parts[0]);
  20.                 frequency.set(Integer.parseInt(parts[1]));
  21.                 context.write(frequency, word); // 倒置键值对,频率作为 key
  22.             }
  23.         }
  24.     }
  25.     public static class TopKReducer extends Reducer<IntWritable, Text, Text, IntWritable> {
  26.         private TreeMap<Integer, String> topKMap = new TreeMap<>();
  27.         private int K = 10; // 设置需要的 Top K 值
  28.         public void reduce(IntWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
  29.             for (Text val : values) {
  30.                 topKMap.put(key.get(), val.toString());
  31.                 if (topKMap.size() > K) {
  32.                     topKMap.remove(topKMap.firstKey()); // 保持大小为 K
  33.                 }
  34.             }
  35.         }
  36.         protected void cleanup(Context context) throws IOException, InterruptedException {
  37.             for (Integer freq : topKMap.descendingKeySet()) {
  38.                 context.write(new Text(topKMap.get(freq)), new IntWritable(freq));
  39.             }
  40.         }
  41.     }
  42.     public static void main(String[] args) throws Exception {
  43.         Configuration conf = new Configuration();
  44.         Job job = Job.getInstance(conf, "top k words");
  45.         job.setJarByClass(TopKWords.class);
  46.         job.setMapperClass(SwapMapper.class);
  47.         job.setReducerClass(TopKReducer.class);
  48.         job.setOutputKeyClass(IntWritable.class);
  49.         job.setOutputValueClass(Text.class);
  50.         FileInputFormat.addInputPath(job, new Path(args[0]));
  51.         FileOutputFormat.setOutputPath(job, new Path(args[1]));
  52.         System.exit(job.waitForCompletion(true) ? 0 : 1);
  53.     }
  54. }
复制代码

题目 5: 日志分析


  1. import org.apache.hadoop.conf.Configuration;
  2. import org.apache.hadoop.fs.Path;
  3. import org.apache.hadoop.io.IntWritable;
  4. import org.apache.hadoop.io.Text;
  5. import org.apache.hadoop.mapreduce.Job;
  6. import org.apache.hadoop.mapreduce.Mapper;
  7. import org.apache.hadoop.mapreduce.Reducer;
  8. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
  9. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
  10. import java.io.IOException;
  11. public class LogAnalysis {
  12.     public static class LogMapper extends Mapper<Object, Text, Text, IntWritable> {
  13.         private final static IntWritable one = new IntWritable(1);
  14.         public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
  15.             String[] parts = value.toString().split(" ");
  16.             if (parts.length > 0) {
  17.                 String ip = parts[0]; // 提取 IP
  18.                 context.write(new Text(ip), one);
  19.             }
  20.         }
  21.     }
  22.     public static class LogReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
  23.         public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
  24.             int sum = 0;
  25.             for (IntWritable val : values) {
  26.                 sum += val.get();
  27.             }
  28.             context.write(key, new IntWritable(sum));
  29.         }
  30.     }
  31.     public static void main(String[] args) throws Exception {
  32.         Configuration conf = new Configuration();
  33.         Job job = Job.getInstance(conf, "log analysis");
  34.         job.setJarByClass(LogAnalysis.class);
  35.         job.setMapperClass(LogMapper.class);
  36.         job.setReducerClass(LogReducer.class);
  37.         job.setOutputKeyClass(Text.class);
  38.         job.setOutputValueClass(IntWritable.class);
  39.         FileInputFormat.addInputPath(job, new Path(args[0]));
  40.         FileOutputFormat.setOutputPath(job, new Path(args[1]));
  41.         System.exit(job.waitForCompletion(true) ? 0 : 1);
  42.     }
  43. }
复制代码
 题目 6: 用户购买分析


  1. import org.apache.hadoop.conf.Configuration;
  2. import org.apache.hadoop.fs.Path;
  3. import org.apache.hadoop.io.DoubleWritable;
  4. import org.apache.hadoop.io.Text;
  5. import org.apache.hadoop.mapreduce.Job;
  6. import org.apache.hadoop.mapreduce.Mapper;
  7. import org.apache.hadoop.mapreduce.Reducer;
  8. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
  9. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
  10. import java.io.IOException;
  11. public class UserPurchaseAnalysis {
  12.     public static class PurchaseMapper extends Mapper<Object, Text, Text, DoubleWritable> {
  13.         public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
  14.             String[] parts = value.toString().split(" ");
  15.             if (parts.length == 2) {
  16.                 String userId = parts[0];
  17.                 double amount = Double.parseDouble(parts[1]);
  18.                 context.write(new Text(userId), new DoubleWritable(amount));
  19.             }
  20.         }
  21.     }
  22.     public static class PurchaseReducer extends Reducer<Text, DoubleWritable, Text, DoubleWritable> {
  23.         public void reduce(Text key, Iterable<DoubleWritable> values, Context context) throws IOException, InterruptedException {
  24.             double sum = 0.0;
  25.             for (DoubleWritable val : values) {
  26.                 sum += val.get();
  27.             }
  28.             context.write(key, new DoubleWritable(sum));
  29.         }
  30.     }
  31.     public static void main(String[] args) throws Exception {
  32.         Configuration conf = new Configuration();
  33.         Job job = Job.getInstance(conf, "user purchase analysis");
  34.         job.setJarByClass(UserPurchaseAnalysis.class);
  35.         job.setMapperClass(PurchaseMapper.class);
  36.         job.setReducerClass(PurchaseReducer.class);
  37.         job.setOutputKeyClass(Text.class);
  38.         job.setOutputValueClass(DoubleWritable.class);
  39.         FileInputFormat.addInputPath(job, new Path(args[0]));
  40.         FileOutputFormat.setOutputPath(job, new Path(args[1]));
  41.         System.exit(job.waitForCompletion(true) ? 0 : 1);
  42.     }
  43. }
复制代码
题目 7: 倒排索引 (Inverted Index)


  1. import org.apache.hadoop.conf.Configuration;
  2. import org.apache.hadoop.fs.Path;
  3. import org.apache.hadoop.io.Text;
  4. import org.apache.hadoop.mapreduce.Job;
  5. import org.apache.hadoop.mapreduce.Mapper;
  6. import org.apache.hadoop.mapreduce.Reducer;
  7. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
  8. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
  9. import java.io.IOException;
  10. import java.util.HashSet;
  11. public class InvertedIndex {
  12.     public static class IndexMapper extends Mapper<Object, Text, Text, Text> {
  13.         private Text word = new Text();
  14.         private Text documentId = new Text();
  15.         public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
  16.             String[] line = value.toString().split("\t", 2); // 输入格式: 文档ID \t 文本内容
  17.             if (line.length < 2) return;
  18.             documentId.set(line[0]);
  19.             String[] words = line[1].split("\\s+");
  20.             for (String w : words) {
  21.                 word.set(w);
  22.                 context.write(word, documentId);
  23.             }
  24.         }
  25.     }
  26.     public static class IndexReducer extends Reducer<Text, Text, Text, Text> {
  27.         public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
  28.             HashSet<String> docIds = new HashSet<>();
  29.             for (Text docId : values) {
  30.                 docIds.add(docId.toString());
  31.             }
  32.             context.write(key, new Text(String.join(", ", docIds)));
  33.         }
  34.     }
  35.     public static void main(String[] args) throws Exception {
  36.         Configuration conf = new Configuration();
  37.         Job job = Job.getInstance(conf, "inverted index");
  38.         job.setJarByClass(InvertedIndex.class);
  39.         job.setMapperClass(IndexMapper.class);
  40.         job.setReducerClass(IndexReducer.class);
  41.         job.setOutputKeyClass(Text.class);
  42.         job.setOutputValueClass(Text.class);
  43.         FileInputFormat.addInputPath(job, new Path(args[0]));
  44.         FileOutputFormat.setOutputPath(job, new Path(args[1]));
  45.         System.exit(job.waitForCompletion(true) ? 0 : 1);
  46.     }
  47. }
复制代码
 题目 8: 用户商品共现分析


  1. import org.apache.hadoop.conf.Configuration;
  2. import org.apache.hadoop.fs.Path;
  3. import org.apache.hadoop.io.Text;
  4. import org.apache.hadoop.mapreduce.Job;
  5. import org.apache.hadoop.mapreduce.Mapper;
  6. import org.apache.hadoop.mapreduce.Reducer;
  7. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
  8. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
  9. import java.io.IOException;
  10. import java.util.ArrayList;
  11. public class CoOccurrence {
  12.     public static class CoOccurrenceMapper extends Mapper<Object, Text, Text, Text> {
  13.         private Text user = new Text();
  14.         private Text itemList = new Text();
  15.         public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
  16.             String[] parts = value.toString().split("\\s+");
  17.             if (parts.length < 2) return;
  18.             user.set(parts[0]);
  19.             itemList.set(String.join(",", parts, 1, parts.length));
  20.             context.write(user, itemList);
  21.         }
  22.     }
  23.     public static class CoOccurrenceReducer extends Reducer<Text, Text, Text, Text> {
  24.         public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
  25.             ArrayList<String> items = new ArrayList<>();
  26.             for (Text val : values) {
  27.                 String[] parts = val.toString().split(",");
  28.                 for (String item : parts) {
  29.                     items.add(item);
  30.                 }
  31.             }
  32.             for (int i = 0; i < items.size(); i++) {
  33.                 for (int j = i + 1; j < items.size(); j++) {
  34.                     String pair = items.get(i) + " " + items.get(j);
  35.                     context.write(new Text(pair), new Text("1"));
  36.                 }
  37.             }
  38.         }
  39.     }
  40.     public static void main(String[] args) throws Exception {
  41.         Configuration conf = new Configuration();
  42.         Job job = Job.getInstance(conf, "co-occurrence");
  43.         job.setJarByClass(CoOccurrence.class);
  44.         job.setMapperClass(CoOccurrenceMapper.class);
  45.         job.setReducerClass(CoOccurrenceReducer.class);
  46.         job.setOutputKeyClass(Text.class);
  47.         job.setOutputValueClass(Text.class);
  48.         FileInputFormat.addInputPath(job, new Path(args[0]));
  49.         FileOutputFormat.setOutputPath(job, new Path(args[1]));
  50.         System.exit(job.waitForCompletion(true) ? 0 : 1);
  51.     }
  52. }
复制代码
 题目 9: 数据去重

​​​​​​​

  1. import org.apache.hadoop.conf.Configuration;
  2. import org.apache.hadoop.fs.Path;
  3. import org.apache.hadoop.io.Text;
  4. import org.apache.hadoop.mapreduce.Job;
  5. import org.apache.hadoop.mapreduce.Mapper;
  6. import org.apache.hadoop.mapreduce.Reducer;
  7. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
  8. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
  9. import java.io.IOException;
  10. public class Deduplication {
  11.     public static class DedupMapper extends Mapper<Object, Text, Text, Text> {
  12.         public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
  13.             context.write(value, new Text(""));
  14.         }
  15.     }
  16.     public static class DedupReducer extends Reducer<Text, Text, Text, Text> {
  17.         public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
  18.             context.write(key, new Text(""));
  19.         }
  20.     }
  21.     public static void main(String[] args) throws Exception {
  22.         Configuration conf = new Configuration();
  23.         Job job = Job.getInstance(conf, "data deduplication");
  24.         job.setJarByClass(Deduplication.class);
  25.         job.setMapperClass(DedupMapper.class);
  26.         job.setReducerClass(DedupReducer.class);
  27.         job.setOutputKeyClass(Text.class);
  28.         job.setOutputValueClass(Text.class);
  29.         FileInputFormat.addInputPath(job, new Path(args[0]));
  30.         FileOutputFormat.setOutputPath(job, new Path(args[1]));
  31.         System.exit(job.waitForCompletion(true) ? 0 : 1);
  32.     }
  33. }
复制代码
题目 10: 分组统计 (Group By)


  1. import org.apache.hadoop.conf.Configuration;
  2. import org.apache.hadoop.fs.Path;
  3. import org.apache.hadoop.io.IntWritable;
  4. import org.apache.hadoop.io.Text;
  5. import org.apache.hadoop.mapreduce.Job;
  6. import org.apache.hadoop.mapreduce.Mapper;
  7. import org.apache.hadoop.mapreduce.Reducer;
  8. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
  9. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
  10. import java.io.IOException;
  11. public class GroupBy {
  12.     public static class GroupMapper extends Mapper<Object, Text, Text, IntWritable> {
  13.         public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
  14.             String[] parts = value.toString().split("\\s+");
  15.             if (parts.length == 2) {
  16.                 String group = parts[0];
  17.                 int number = Integer.parseInt(parts[1]);
  18.                 context.write(new Text(group), new IntWritable(number));
  19.             }
  20.         }
  21.     }
  22.     public static class GroupReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
  23.         public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
  24.             int sum = 0;
  25.             for (IntWritable val : values) {
  26.                 sum += val.get();
  27.             }
  28.             context.write(key, new IntWritable(sum));
  29.         }
  30.     }
  31.     public static void main(String[] args) throws Exception {
  32.         Configuration conf = new Configuration();
  33.         Job job = Job.getInstance(conf, "group by");
  34.         job.setJarByClass(GroupBy.class);
  35.         job.setMapperClass(GroupMapper.class);
  36.         job.setReducerClass(GroupReducer.class);
  37.         job.setOutputKeyClass(Text.class);
  38.         job.setOutputValueClass(IntWritable.class);
  39.         FileInputFormat.addInputPath(job, new Path(args[0]));
  40.         FileOutputFormat.setOutputPath(job, new Path(args[1]));
  41.         System.exit(job.waitForCompletion(true) ? 0 : 1);
  42.     }
  43. }
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

万万哇

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表