根据上面两篇文章,下面是我在自己的ubuntu上的运行过程。文字基本采用博文使用Python实现Hadoop MapReduce程序, 打字很浪费时间滴。
在这个实例中,我将会向大家介绍如何使用Python 为 Hadoop编写一个简单的MapReduce程序。
尽管Hadoop 框架是使用Java编写的但是我们仍然需要使用像C++、Python等语言来实现
Hadoop程序。尽管Hadoop官方网站给的示例程序是使用Jython编写并打包成Jar文件,这样显然造成了不便,其实,不一定非要这样来实现,
我们可以使用Python与Hadoop 关联进行编程,看看位于/src/examples/python/WordCount.py
的例子,你将了解到我在说什么。
我们想要做什么?
我们将编写一个简单的 MapReduce 程序,使用的是C-Python,而不是Jython编写后打包成jar包的程序。
我们的这个例子将模仿 WordCount 并使用Python来实现,例子通过读取文本文件来统计出单词的出现次数。结果也以文本形式输出,每一行包含一个单词和单词出现的次数,两者中间使用制表符来想间隔。
先决条件
编写这个程序之前,你学要架设好Hadoop 集群,这样才能不会在后期工作抓瞎。如果你没有架设好,那么在后面有个简明教程来教你在Ubuntu Linux 上搭建(同样适用于其他发行版linux、unix)
如何在Ubuntu Linux 上搭建hadoop的单节点模式和伪分布模式,请参阅博文Ubuntu上搭建Hadoop环境(单机模式+伪分布模式)
Python的MapReduce代码
使用Python编写MapReduce代码的技巧就在于我们使用了 HadoopStreaming 来帮助我们在Map 和
Reduce间传递数据通过STDIN (标准输入)和STDOUT
(标准输出).我们仅仅使用Python的sys.stdin来输入数据,使用sys.stdout输出数据,这样做是因为
HadoopStreaming会帮我们办好其他事。这是真的,别不相信!
Map: mapper.py
将下列的代码保存在/usr/local/hadoop/mapper.py中,他将从STDIN读取数据并将单词成行分隔开,生成一个列表映射单词与发生次数的关系:
注意:要确保这个脚本有足够权限(chmod +x mapper.py)。
#!/usr/bin/envpython
importsys
#inputcomesfromSTDIN(standardinput)
forlineinsys.stdin:
#removeleadingandtrailingwhitespace
line=line.strip()
#splitthelineintowords
words=line.split()
#increasecounters
forwordinwords:
#writetheresultstoSTDOUT(standardoutput);
#whatweoutputherewillbetheinputforthe
#Reducestep,i.e.theinputforreducer.py
#tab-delimited;thetrivialwordcountis1
print’%s %s’%(word,1)
在这个脚本中,并不计算出单词出现的总数,它将输出 " 1"
迅速地,尽管可能会在输入中出现多次,计算是留给后来的Reduce步骤(或叫做程序)来实现。当然你可以改变下编码风格,完全
尊重你的习惯。Reduce: reducer.py
将代码存储在/usr/local/hadoop/reducer.py 中,这个脚本的作用是从mapper.py 的STDIN中读取结果,然后计算每个单词出现次数的总和,并输出结果到STDOUT。
同样,要注意脚本权限:chmod +x reducer.py
#!/usr/bin/envpython
fromoperatorimportitemgetter
importsys
current_word=None
current_count=0
word=None
#inputcomesfromSTDIN
forlineinsys.stdin:
#removeleadingandtrailingwhitespace
line=line.strip()
#parsetheinputwegotfrommapper.py
word,count=line.split(’ ',1)
#convertcount(currentlyastring)toint
try:
count=int(count)
exceptValueError:
#countwasnotanumber,sosilently
#ignore/discardthisline
continue
#thisIF-switchonlyworksbecauseHadoopsortsmapoutput
#bykey(here:word)beforeitispassedtothereducer
ifcurrent_word==word:
current_count+=count
else:
ifcurrent_word:
#writeresulttoSTDOUT
print’%s %s’%(current_word,current_count)
current_count=count
current_word=word
#donotforgettooutputthelastwordifneeded!
ifcurrent_word==word:
print’%s %s’%(current_word,current_count)
测试你的代码(cat data | map | sort | reduce)
我建议你在运行MapReduce job测试前尝试手工测试你的mapper.py 和 reducer.py脚本,以免得不到任何返回结果
这里有一些建议,关于如何测试你的Map和Reduce的功能:
hadoop@derekUbun:/usr/local/hadoop$echo"foofooquuxlabsfoobarquux"|./mapper.py
foo1
foo1
quux1
labs1
foo1
bar1
quux1
hadoop@derekUbun:/usr/local/hadoop$echo"foofooquuxlabsfoobarquux"|./mapper.py|sort|./reducer.py
bar1
foo3
labs1
quux2
# using one of the ebooks as example input
# (see below on where to get the ebooks)
hadoop@derekUbun:/usr/local/hadoop$catbook/book.txt|./mapper.pysubscribe1
to1
our1
email1
newsletter1
to1
hear1
about1
new1
eBooks.1
在Hadoop平台上运行Python脚本
为了这个例子,我们将需要一本电子书,把它放在/usr/local/hadpoop/book/book.txt之下
hadoop@derekUbun:/usr/local/hadoop$ls-lbook
总用量636
-rw-rw-r–1derekderek6496693月1212:22book.txt
复制本地数据到HDFS
在我们运行MapReduce job 前,我们需要将本地的文件复制到HDFS中:
hadoop@derekUbun:/usr/local/hadoop$hadoopdfs-copyFromLocal/usr/local/hadoop/bookbook
hadoop@derekUbun:/usr/local/hadoop$hadoopdfs-ls
Found3items
drwxr-xr-x-hadoopsupergroup02013-03-1215:56/user/hadoop/book
执行 MapReduce job现在,一切准备就绪,我们将在运行Python MapReduce job
在Hadoop集群上。像我上面所说的,我们使用的是HadoopStreaming
帮助我们传递数据在Map和Reduce间并通过STDIN和STDOUT,进行标准化输入输出。
hadoop@derekUbun:/usr/local/hadoop$hadoopjarcontrib/streaming/hadoop-streaming-1.1.2.jar
-mapper/usr/local/hadoop/mapper.py
-reducer/usr/local/hadoop/reducer.py
-inputbook/*
-outputbook-output
在运行中,如果你想更改Hadoop的一些设置,如增加Reduce任务的数量,你可以使用“-jobconf”选项:
hadoop@derekUbun:/usr/local/hadoop$hadoopjarcontrib/streaming/hadoop-streaming-1.1.2.jar
-jobconfmapred.reduce.tasks=4
-mapper/usr/local/hadoop/mapper.py
-reducer/usr/local/hadoop/reducer.py
-inputbook/*
-outputbook-output
如果上面两个运行出错,请参考下面一段代码。注意,重新运行,需要删除dfs中的output文件
bin/hadoopjarcontrib/streaming/hadoop-streaming-1.1.2.jar
-mappertask1/mapper.py
-filetask1/mapper.py
-reducertask1/reducer.py
-filetask1/reducer.py
-inputurl
-outputurl-output
-jobconfmapred.reduce.tasks=3
一个重要的备忘是关于Hadoop does not honor mapred.map.tasks 这个任务将会读取HDFS目录下的book并处理他们,将结果存储在独立的结果文件中,并存储在HDFS目录下的book-output目录。之前执行的结果如下:
hadoop@derekUbun:/usr/local/hadoop$hadoopjarcontrib/streaming/hadoop-streaming-1.1.2.jar-jobconfmapred.reduce.tasks=4-mapper/usr/local/hadoop/mapper.py-reducer/usr/local/hadoop/reducer.py-inputbook/*-outputbook-output
13/03/1216:01:05WARNstreaming.StreamJob:-jobconfoptionisdeprecated,pleaseuse-Dinstead.
packageJobJar:[/usr/local/hadoop/tmp/hadoop-unjar4835873410426602498/][]/tmp/streamjob5047485520312501206.jartmpDir=null
13/03/1216:01:06INFOutil.NativeCodeLoader:Loadedthenative-hadooplibrary
13/03/1216:01:06WARNsnappy.LoadSnappy:Snappynativelibrarynotloaded
13/03/1216:01:06INFOmapred.FileInputFormat:Totalinputpathstoprocess:1
13/03/1216:01:06INFOstreaming.StreamJob:getLocalDirs():[/usr/local/hadoop/tmp/mapred/local]
13/03/1216:01:06INFOstreaming.StreamJob:Runningjob:job_201303121448_0010
13/03/1216:01:06INFOstreaming.StreamJob:Tokillthisjob,run:
13/03/1216:01:06INFOstreaming.StreamJob:/usr/local/hadoop/libexec/…/bin/hadoopjob-Dmapred.job.tracker=localhost:9001-killjob_201303121448_0010
13/03/1216:01:06INFOstreaming.StreamJob:TrackingURL:http://localhost:50030/jobdetails.jspjobid=job_201303121448_0010
13/03/1216:01:07INFOstreaming.StreamJob:map0%reduce0%
13/03/1216:01:10INFOstreaming.StreamJob:map100%reduce0%
13/03/1216:01:17INFOstreaming.StreamJob:map100%reduce8%
13/03/1216:01:18INFOstreaming.StreamJob:map100%reduce33%
13/03/1216:01:19INFOstreaming.StreamJob:map100%reduce50%
13/03/1216:01:26INFOstreaming.StreamJob:map100%reduce67%
13/03/1216:01:27INFOstreaming.StreamJob:map100%reduce83%
13/03/1216:01:28INFOstreaming.StreamJob:map100%reduce100%
13/03/1216:01:29INFOstreaming.StreamJob:Jobcomplete:job_201303121448_0010
13/03/1216:01:29INFOstreaming.StreamJob:Output:book-output
hadoop@derekUbun:/usr/local/hadoop$
如你所见到的上面的输出结果,Hadoop 同时还提供了一个基本的WEB接口显示统计结果和信息。
当Hadoop集群在执行时,你可以使用浏览器访问 http://localhost:50030/ :
检查结果是否输出并存储在HDFS目录下的book-output中:
hadoop@derekUbun:/usr/local/hadoop$hadoopdfs-lsbook-output
Found6items
-rw-r–r–2hadoopsupergroup02013-03-1216:01/user/hadoop/book-output/_SUCCESS
drwxr-xr-x-hadoopsupergroup02013-03-1216:01/user/hadoop/book-output/_logs
-rw-r–r–2hadoopsupergroup332013-03-1216:01/user/hadoop/book-output/part-00000
-rw-r–r–2hadoopsupergroup602013-03-1216:01/user/hadoop/book-output/part-00001
-rw-r–r–2hadoopsupergroup542013-03-1216:01/user/hadoop/book-output/part-00002
-rw-r–r–2hadoopsupergroup472013-03-1216:01/user/hadoop/book-output/part-00003
hadoop@derekUbun:/usr/local/hadoop$
可以使用dfs -cat 命令检查文件目录
hadoop@derekUbun:/usr/local/hadoop$hadoopdfs-catbook-output/part-00000
about1
eBooks.1
the1
to2
hadoop@derekUbun:/usr/local/hadoop$
下面是原英文作者mapper.py和reducer.py的两个修改版本:
mapper.py
#!/usr/bin/envpython
“”“AmoreadvancedMapper,usingPythoniteratorsandgenerators.”“”
importsys
defread_input(file):
forlineinfile:
#splitthelineintowords
yieldline.split()
defmain(separator=’ '):
#inputcomesfromSTDIN(standardinput)
data=read_input(sys.stdin)
forwordsindata:
#writetheresultstoSTDOUT(standardoutput);
#whatweoutputherewillbetheinputforthe
#Reducestep,i.e.theinputforreducer.py
#tab-delimited;thetrivialwordcountis1
forwordinwords:
print’%s%s%d’%(word,separator,1)
if__name__==“__main__”:
main()
reducer.py
#!/usr/bin/envpython
“”“AmoreadvancedReducer,usingPythoniteratorsandgenerators.”“”
fromitertoolsimportgroupby
fromoperatorimportitemgetter
importsys
defread_mapper_output(file,separator=’ '):
forlineinfile:
yieldline.rstrip().split(separator,1)
defmain(separator=’ '):
#inputcomesfromSTDIN(standardinput)
data=read_mapper_output(sys.stdin,separator=separator)
#groupbygroupsmultipleword-countpairsbyword,
#andcreatesaniteratorthatreturnsconsecutivekeysandtheirgroup:
#current_word-stringcontainingaword(thekey)
#group-iteratoryieldingall[“”,“”]items
forcurrent_word,groupingroupby(data,itemgetter(0)):
try:
total_count=sum(int(count)forcurrent_word,countingroup)
print"%s%s%d"%(current_word,separator,total_count)
exceptValueError:
#countwasnotanumber,sosilentlydiscardthisitem
pass
if__name__==“__main__”:
main()