背景
PySpark 通过 RPC server 来和底层的 Spark 做交互,通过 Py4j 来实现利用 API 调用 Spark 核心。
Spark (written in Scala) 速度比 Hadoop 快很多。Spark 配置可以各种参数,包括并行数目、资源占用以及数据存储的方式等等
Resilient Distributed Dataset (RDD) 可以被并行运算的 Spark 单元。它是 immutable, partitioned collection of elements
安装 PySpark
pip install pyspark
使用
连接 Spark Cluster
from pyspark import SparkContext, SparkConf
conf = SparkConf().setAppName("sparkAppExample")
sc = SparkContext(conf=conf)
Spark DataFrame
from pyspark.sql import SparkSession
spark = SparkSession.builder \
.master("local") \
.appName("Word Count") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
# 如果使用 hive table 则加上 .enableHiveSupport()
Spark Config 条目
- 配置大全网址
DataFrame 结构使用说明
PySpark 的 DataFrame 很像 pandas 里的 DataFrame 结构
读取本地文件
# Define the Data
import json
people = [
{
'name': 'Li', 'age': 12, 'address': {
'country': 'China', 'city': 'Nanjing'}},
{
'name': 'Richard', 'age': 14, 'address': {
'country': 'USA', 'city': 'Los Angeles'}}