在前一篇文章中我们使用了hadoop-MapReduce-streaming合并数据。这里我们使用相同的数据文件,但改用在PySparkshell下使用Spark完成这个任务。PySpark的交互性显然比使用MapReduce更好。
首先保证已经安装PySpark。
1. 启动PySpark
PYSPARK_DRIVER_PYTHON=ipythonpyspark
2. 载入数据
a. 载入存储在HDFS上的数据
fileA =sc.textFile("3-spark_join/input/join1_FileA.txt")
fileB =sc.textFile("3-spark_join/input/join1_FileB.txt")
b. 检查数据已经载入
<span style="white-space:pre"> </span>fileA.collect()
fileB.collect()
3. Mapper函数
a. 分别为FileA和FileB编写mapper函数,把读入的数据分割为<key, value>
def split_fileA(line):
# split the input line in word and count on the comma
key_value = line.split(",")
# turn the count to an integer
word = key_value[0]
count = int(key_value[1])
return (word,count)
def split_fileB(line):
# split the input line into word, date and count_string
key_value = line.split(",")
key_in = key_value[0].split(" ")
word = key_in[1]
date = key_in[0]
count_string = key_value[1]
return (word, date + " " +count_string)
b. 可以用一个简单的数据检查函数
<span style="white-space:pre"> </span>test_line = "able,991"
<span style="white-space:pre"> </span>split_fileA(test_line)
c. 现在可以用在FileA和FileB上了
<span style="white-space:pre"> </span>fileA_data =fileA.map(split_fileA)
fileB_data= fileB.map(split_fileB)
d. 检查输出
<span style="white-space:pre"> </span>fileA_data.collect()
<span style="white-space:pre"> </span>fileB_data.collect()
e. 应该得到
<span style="white-space:pre"> </span>Out[]: [(u'able', 991), (u'about',11), (u'burger', 15), (u'actor', 22)]
<span style="white-space:pre"> </span>Out[]:
<span style="white-space:pre"> </span>[(u'able', u'Jan-01 5'),
<span style="white-space:pre"> </span>(u'about', u'Feb-02 3'),
<span style="white-space:pre"> </span>(u'about', u'Mar-03 8 '),
<span style="white-space:pre"> </span>(u'able', u'Apr-04 13'),
<span style="white-space:pre"> </span>(u'actor', u'Feb-22 3'),
<span style="white-space:pre"> </span>(u'burger', u'Feb-23 5'),
<span style="white-space:pre"> </span>(u'burger', u'Mar-08 2'),
<span style="white-space:pre"> </span>(u'able', u'Dec-15 100')]
4. Spark本身有join函数,可以把有相同key的两个数据集合并,如:(K, V)和(K, W)合并为(K,(V, W))
fileB_joined_fileA =fileB_data.join(fileA_data)
5. 检查结果
fileB_joined_fileA.collect()
应该得到:
Out[20]:
[(u'about', (u'Feb-02 3', 11)),
(u'about', (u'Mar-03 8', 11)),
(u'able', (u'Jan-01 5', 991)),
(u'able', (u'Apr-04 13', 991)),
(u'able', (u'Dec-15 100', 991)),
(u'actor', (u'Feb-22 3', 22)),
(u'burger', (u'Feb-23 5', 15)),
(u'burger', (u'Mar-08 2', 15))]