實驗環境:Linux環境、python3環境
實驗要求:
一、創建map.py檔案,注意要點:
1、對空白行的處理,可判斷 line[0] != ‘’
2、時間資料包含年月日,只需截取年份
3、可以將每行訂單資料都算為1筆
4、目標輸出格式:年份,數額
二、自行撰寫reduce.py代碼,注意要點
1、可以將資料的行數當成筆數
2、輸出時應按年份排好序
3、目標輸出格式: 年份,筆數-總額
(總額要求轉化成k且保留兩位小數,如13572468.98 -> 13572.46k)
實驗思想:
1、map環節:映射,即選出所需要處理的欄位,從這道題的實驗要求來看,map最后處理出來的鍵值對應為:(k1,v1)=(年份,數額)
2、reduce環節:規約,將關鍵字相同的資料進行運算處理,reduce最后處理出來的鍵值對為:(k2,v2)=(年份,(筆數—總額))
實作功能環節
map功能的實作
#map功能的實作
import sys
for line in sys.stdin:
if line[0]!="" :
col = line.strip().split(',')
col1=col[2].strip().split('-')
col[2]=col1[0]
print(col[2],',',col[6])
reduce功能的實作
#reduce功能的實作
#!/bin/env python
# encoding: utf-8
from operator import itemgetter
import itertools
import sys
def read_mapper_output(file, separator = ','):
for line in file:
yield line.rstrip().split(separator,1)
stdin_generator=read_mapper_output(sys.stdin, ',')
for year, sals in itertools.groupby(stdin_generator,itemgetter(0) ):
count=0
total_sal=0
for year,cur_sal in sals:
count = count+1
total_sal=total_sal + float(cur_sal)
print(year,'\t',count,'\t','%.2f'%(total_sal/1000))
運行結果
map的運行結果

本地管道測驗map代碼
cat sales.csv | python map.py
map-reduce的運行結果

map-reduce本地管道測驗:
cat sales.csv | python map.py | sort -k 1 | python reduce.py
在Hadoop集群里實作MapReduce功能
一、打開命令列視窗,啟動Hadoop
cd /opt/hadoop/sbin
hadoop namenode -format #格式化名稱節點
start-all.sh #啟動服務器
jps #查看行程
二、在HDFS上創建目錄/001/input,并將資料檔案上傳至HDFS
hdfs dfs -mkdir -p /001/input #創建檔案夾
hdfs dfs -put sales.csv /001/input #上傳檔案到集群檔案夾里
hdfs dfs -ls /001/input #查看是否上傳成功
三、新建一個XX.sh檔案
$HADOOP_HOME/bin/hadoop jar \
$HADOOP_HOME/share/hadoop/tools/lib/hadoop-streaming-2.7.3.jar \
-D stream.non.zero.exit.is.failure=false \ #對于錯誤不報出
-D mapred.job.name="streaming_count" \ #作業的名稱的命名,在瀏覽器輸入:localhost:8088/,可以看到作業名,
-D mapred.job.priority=HIGH \ #先執行優先權高的作業
-files "/home/ubuntu/PycharmProjects/untitled/map.py,/home/ubuntu/PycharmProjects/untitled/reduce.py" \
-input /001/input/sales.csv \
-output /001/input/out001 \
-mapper "python3 map.py" \
-reducer "python3 reduce.py"
然后在XX.sh檔案夾下打開命令視窗輸入以下代碼即可以運行出結果:
sh XX.sh
用上面指令運行出來的結果如下:
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/201022.html
標籤:其他
