创建DataFrame在Spark SQL中,开发者可以非常便捷地将各种内、外部的单机、分布式数据转换为DataFrame。以下Python示例代码充分体现了Spark SQL 1.3.0中DataFrame数据源的丰富多样和简单易用:
- # 从Hive中的users表构造DataFrame
- users = sqlContext.table("users")
- # 加载S3上的JSON文件
- logs = sqlContext.load("s3n://path/to/data.json", "json")
- # 加载HDFS上的Parquet文件
- clicks = sqlContext.load("hdfs://path/to/data.parquet", "parquet")
- # 通过JDBC访问MySQL
- comments = sqlContext.jdbc("jdbc:mysql://localhost/comments", "user")
- # 将普通RDD转变为DataFrame
- rdd = sparkContext.textFile("article.txt")
- .flatMap(lambda line: line.split())
- .map(lambda word: (word, 1))
- .reduceByKey(lambda a, b: a + b)
- wordCounts = sqlContext.createDataFrame(rdd, ["word", "count"])
- # 将本地数据容器转变为DataFrame
- data = [("Alice", 21), ("Bob", 24)]
- people = sqlContext.createDataFrame(data, ["name", "age"])
- # 将Pandas DataFrame转变为Spark DataFrame(Python API特有功能)
- sparkDF = sqlContext.createDataFrame(pandasDF)