本次用python进行测试。
首先编写Mapper和Reducer脚本,从stdin读取数据,输出到stdout。
mapper.py
#!/usr/bin/env python
import sys;
for line in sys.stdin:
line = line.strip();
words = line.split();
for w in words:
print('%s\t%d' % (w, 1))
reducer.py
#!/usr/bin/env python
import sys;
wordCount = {};
for line in sys.stdin:
line = line.strip();
w,c = line.split();
try:
c = int(c);
wordCount[w] = wordCount.get(w, 0) + c;
except ValueError:
pass;
for k,v in wordCount.items():
print('%s\t%d' % (k, v));
然后创建一个原始文本文件,上传到hdfs某路径下。
接下来运行脚本
hadoop jar /usr/local/hadoop/share/hadoop/tools/lib/hadoop-streaming-2.6.4.jar -input /user/xlq/test/input.txt -output /user/xlq/test/output.txt -file *.py -mapper mapper.py -reducer reducer.py -numReduceTasks 1
第三个参数是你本机的hadoop streaminng jar包路径
-input和-output参数是hdfs上原始文本文件的路径和希望的输出路径地址
-file参数指定本机上python脚本的位置,对我来说就是当前路径下所有.py文件。 -mapper和-reducer里只需要写文件名即可,不需要完整的文件路径
最后就可以从hdfs上获取最终结果
在运行时可能会遇到下面的错误
Error: java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 1
产生原因有很多,具体参见 http://stackoverflow.com/questions/4460522/hadoop-streaming-job-failed-error-in-python
在任务运行过程中(运行结束后再看history就看不出来了)查看UI上某次attempt的stderr log,就能看出具体异常原因。对于我来说,是因为自己写的python脚本里使用了2.6版本不支持的语法造成的。。。(集群node上的python版本太老了)