TransFormation:
1、值类型:
map:
将数据转化成 (key,value)键值对的格式 :map(lambda x: (x, 1))
flatmap:
数据扁平化,以空格字符分割将数据扁平化,搭配函数使用:flatMap(lambda a: re.split('\s+', a))
filter:
把满足条件的筛选出来,去掉不满足条件的: file_rdd.filter(lambda line: len(line.strip()) > 0)
mapValue:
搭配 operator 使用 mapValue(数据类型) ,其中数据类型可以是:列表、元组……
2、双值类型:
union
subtract
intersection
distinct
rdd1=sc.parallelize([1,2,3,4,5])
rdd2=sc.parallelize([1,2,3])
union:全集
din_value=rdd1.union(rdd2)
print(din_value.distinct().collect())
[1, 2, 3,1,2,3,4, 5]
subtract:差集
print(rdd1.subtract(rdd2).collect())
[4, 5]
intersection:交集
print(rdd1.intersection(rdd2).collect())
[1, 2, 3]
distinct:去重,两个数据集union之后得到全集,包含重复数据,使用distinct去重
din_value=rdd1.union(rdd2)
print(din_value.distinct().collect())
[1, 2, 3, 4, 5]
3、key-value值类型:
reduceByKey:
将数据按照value值累加(不是计数)
key2 = rdd3.reduceByKey(lambda x,y:x+y)
print(key2.collect())
[('b', 6), ('c', 3), ('a', 1)]
groupByKey:
groupByKey搭配mapValues()使用:
Examples :
>>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)])
>>> sorted(rdd.groupByKey().mapValues(len).collect()) [('a', 2), ('b', 1)]
>>>sorted(rdd.groupByKey().mapValues(list).collect())
[('a', [1, 1]), ('b', [1])]
mapValues():
mapValues(list).collect()
mapValues(tuple).collect()
括号内接数据类型:列表、元组等,将数据[('b', [2, 4]), ('c', [3]), ('a', [1])]这样输出
sortByKey:
根据value值进行排序,使用 map 进行 key-value的转换:
key2.map(lambda x:(x[1],x[0])).sortByKey(False)
再将结果输出:
print(key3.collect())
[(6, 'b'), (3, 'c'), (1, 'a')]
combineByKey:
所有 ByKey 的底层
rdd2 = rdd1.combineByKey(createCombiner,mergeValue,mergeCombiners)
# todo turns a V into a C (e.g., creates a one-element list)
# todo 取出所有的(key,value)中的 value ,只取 value
def createCombiner(value):
return [value,1]
# todo merge a V into a C (e.g., adds it to the end of a list)
# todo 分区内操作
# todo x相当于[value,1]==>('a',12)==>[12,1]; y代表相同 key 的 value ==>('a',3)==> y=3
# todo x[0]+y相当于把所有相同 key 的 value 都放在了一个列表中,x[1]+1代表了考了几科
def mergeValue(x,y):
return [x[0]+y,x[1]+1]
# todo combine two C's into a single one (e.g., merges the lists)
# todo 分区间操作
# todo 计算分区间的值:将分区间的相同 key 的 value 都累加到一块
def mergeCombiners(x,y):
return [x[0]+y[0],x[1]+y[1]]
本文介绍了SparkRDD中的各种操作,如值类型转换(map、flatMap、filter、mapValue),双值类型操作(union、subtract、intersection、distinct),以及key-value操作(reduceByKey、groupByKey、mapValues、sortByKey和combineByKey)。





