标签:
最近接触到大数据,对于Skpark和Hadoop的料及都停留在第一次听到这个名词时去搜一把看看大概介绍免得跟不上时代的层次。
在实际读了点别人的代码,又自己写了一些之后,虽然谈不上理解加深,至少对于大数据技术的整体布局有了更清晰的认识。
HDFS主要用来存储文件系统,虽然Spark有自己的RDD,但是似乎并未被启用。我需要的数据,是通过Spark服务启动的计算程序,写入HDFS中的。
#这结构怎么看都感觉有点怪。
Spark支持Java、Scala和Python开发,对我来说是个好事。唯一的问题就是如何从HDFS中读取我需要的数据。
Python的HDFS相关包有很多,我使用的是hdfs,根据官方文档的说法,同时支持hdfs和WebHDFS,默认创建client的方式好像是WebHDFS,
需要通过datanode进行文件操作,而HDFS则是通过namenode进行文件操作,在这里卡了很久,也换过snakebite等包,直到把端口换成datanode,才正常连接。
※参照文档:http://fatkun.com/2014/11/httpfs-and-webhdfs.html
hdfs包的安装命令:
sudo pip install hdfs
启动hdfs:
>>> from hdfs.client import Client
>>> client = Client("http://localhost:50070") # 50070: Hadoop默认namenode
>>> dir(client)
[‘__class__‘, ‘__delattr__‘, ‘__dict__‘, ‘__doc__‘, ‘__format__‘, ‘__getattribute__‘, ‘__hash__‘, ‘__init__‘, ‘__module__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__registry__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘__weakref__‘, ‘_append‘, ‘_append_1‘, ‘_create‘, ‘_create_1‘, ‘_delete‘, ‘_get_content_summary‘, ‘_get_file_checksum‘, ‘_get_file_status‘, ‘_get_home_directory‘, ‘_list_status‘, ‘_mkdirs‘, ‘_open‘, ‘_rename‘, ‘_request‘, ‘_session‘, ‘_set_owner‘, ‘_set_permission‘, ‘_set_replication‘, ‘_set_times‘, ‘_timeout‘, ‘checksum‘, ‘content‘, ‘delete‘, ‘download‘, ‘from_options‘, ‘list‘, ‘makedirs‘, ‘parts‘, ‘read‘, ‘rename‘, ‘resolve‘, ‘root‘, ‘set_owner‘, ‘set_permission‘, ‘set_replication‘, ‘set_times‘, ‘status‘, ‘upload‘, ‘url‘, ‘walk‘, ‘write‘]
>>>
其中用到的方法有:
walk() 类似os.walk,返回值也是包含(路径,目录名,文件名)元素的数组,每层迭代。
read() 类似file.read,官方文档的说法是client.read必须在with块里使用:
with client.read(filepath) as fs:
content = fs.read()
write() 写文件,同样需要在with块中使用:
client.write(filepath, data=data_str, encoding=‘utf-8‘)
还有一种写法:
from hdfs.hfile import Hfile
hfile = Hfile(hostname, port, path, mode=‘w‘)
hfile.write(data)
hfile.close()
hfile = Hfile(hostname, port, path)
data = hfile.read()
hfile.close()
在filepath中,如果有不存在的路径,会被直接创建出来。
目前用到的只有这些,后面如果涉及新的方法或者模块,会继续增加。
※ 关于Spark部署任务
Spark部署任务的命令,是spark-submit,语法是
./bin/spark-submit \
--class <main-class>
--master <master-url> \
--deploy-mode <deploy-mode> \
--conf <key>=<value> \
... # other options
<application-jar> \
[application-arguments]
默认可以直接使用Java程序的jar包,Scala是基于Java的,同样可以打包成jar,对于python文件,需要在<application-jar>处使用--py-files定义,单个文件可以直接写出,多个文件的话可以打包成.zip或.egg。
参考:http://spark.apache.org/docs/latest/submitting-applications.html
标签:
原文地址:http://www.cnblogs.com/harelion/p/5398146.html