Broadcast广播变量使用规则如下:
(1)可以使用SparkContext.broadcast([初始值])创建
(2)使用.valuse来读取广播变量的值
(3)Broadcast广播变量被创建后不能修改
例子:
创建kvFruit:
>>> kvFruit = sc.parallelize([(1,"apple"),(2,"orange"),(3,"banala"),(4,"grape")])
>>> kvFruit.collect()
[(1, 'apple'), (2, 'orange'), (3, 'banala'), (4, 'grape')]
使用collectAsMap创建fruitMap字典:
>>> fruitMap = kvFruit.collectAsMap()
>>> fruitMap.collect()
Traceback (most recent call last):
File "
AttributeError: 'dict' object has no attribute 'collect'
>>> print("对照:"+str(fruitMap))
对照:{1: 'apple', 2: 'orange', 3: 'banala', 4: 'grape'}
将fruitMap字典转换为bcFruitMap广播变量:
>>> bcFruitMap = sc.broadcast(fruitMap)
>>> print("字典:"+str(fruitMap))
字典:{1: 'apple', 2: 'orange', 3: 'banala', 4: 'grape'}
创建fruitIds:
>>> fruitId=sc.parallelize([2,4,1,3])
>>> print("水果编号:"+str(fruitId.collect()))
水果编号:[2, 4, 1, 3]
使用广播变量字典进行转换(编号-->名字):
水果编号:[2, 4, 1, 3]
>>> fruitNames = fruitId.map(lambda x:bcFruitMap.value[x]).collect()
>>> print(str(fruitNames))
['orange', 'grape', 'apple', 'banala']