pyspark小demo

发布时间 2023-08-14 16:37:30作者: steve.z
#
#   py_pyspark_demo2.py
#   py_learn
#
#   Created by Z. Steve on 2023/8/13 10:55.
#

import json

# 1. 导入库
from pyspark import SparkConf, SparkContext

# 2. 创建 SparkConf 和 SparkContext 对象
conf = SparkConf().setMaster("local[*]").setAppName("demo2")
sc = SparkContext(conf=conf)

# 3. 读取文件获得文件 rdd. textFile() 会按行读取文本文件, 将每行数据作为一个字符串, 最终将所有行的数据放到一个 list 中
rdd_file = sc.textFile("/Users/stevexhz/PycharmProjects/py_learn/json_data.txt")

# 4. 进行计算操作
# 4.1 取出独立的每个 json 数据. 对每行数据进行 split("|"), 通过 split("|") 获取每个 json 字符串
rdd_json_str = rdd_file.flatMap(lambda x: x.split("|"))
# print(rdd_json_str.collect())                         # 数据格式为 list, list 中的每个元素为一个 json 字符串

# 4.2 将 json 字符串转为 dict 对象
rdd_json_dict = rdd_json_str.map(lambda x: json.loads(x))
# print(rdd_json_dict.collect())                        # list 中的每个元素都是一个 dict 对象

# 4.3 取出字典中的城市 和 销售额组成一个二元元组
rdd_tuple = rdd_json_dict.map(lambda x: (x["district"], int(x["price"])))
# print(rdd_tuple.collect())

# 4.4 按城市分组, 按销售额聚合
rdd_result = rdd_tuple.reduceByKey(lambda a, b: a + b).sortBy(lambda x: x[1], ascending=False, numPartitions=1)
print(rdd_result.collect())


# TODO 2. 所有在售卖的商品类别
rdd_category = rdd_json_dict.map(lambda x: x["category"]).distinct()
print(rdd_category.collect())

# TODO 3. 查看北京地区的所有类别
rdd_bj_category = rdd_json_dict.filter(lambda x: x["district"] == "北京").map(lambda x: x["category"])
print(rdd_bj_category.collect())

sc.stop()

'''
json_data.txt 文件内容


{"id":1, "timestamp": "2023年08月13日11:04:34", "category": "平板电脑", "district": "北京", "price": "5099"}|{"id":2, "timestamp": "2022年08月14日11:04:34", "category": "智能手表", "district": "上海", "price": "25999"}
{"id":3, "timestamp": "2020年09月13日12:04:34", "category": "移动硬盘", "district": "天津", "price": "4099"}|{"id":4, "timestamp": "2021年04月14日11:04:34", "category": "电脑", "district": "上海", "price": "25999"}
{"id":5, "timestamp": "2023年08月13日11:04:34", "category": "智能音箱", "district": "北京", "price": "5099"}|{"id":6, "timestamp": "2022年08月14日11:04:34", "category": "充电宝", "district": "上海", "price": "27999"}|{"id":7, "timestamp": "2023年08月13日11:04:34", "category": "平板电脑", "district": "北京", "price": "5099"}|{"id":8, "timestamp": "2022年08月14日11:04:34", "category": "电脑", "district": "上海", "price": "27999"}
{"id":9, "timestamp": "2023年08月13日11:04:34", "category": "手机", "district": "天津", "price": "195099"}|{"id":10, "timestamp": "2022年08月14日11:04:34", "category": "电脑", "district": "天津", "price": "49999"}|{"id":11, "timestamp": "2023年08月13日11:04:34", "category": "平板电脑", "district": "天津", "price": "15099"}|{"id":12, "timestamp": "2022年08月14日11:04:34", "category": "电脑", "district": "天津", "price": "217999"}

'''