spark3.0-python教程-SparkSQL:DSL方式

说明

通过 SparkSQL,读取 HDFS 上的文件,并使用 DSL 查询分析

准备数据

创建文件 studentInfo.txt

内容如下:

1,李雷,20,男,1.82
2,韩梅梅,21,女,1.65
3,lucy,22,女,1.71
4,lili,22,女,1.71
5,张三,24,男,1.78

上传到 HDFS 任意位置

代码

通过 DataFrame API进行操作,不需要创建视图

import findspark
findspark.init()

from pyspark.sql import  SparkSession

# 创建 SparkSession 对象
spark = SparkSession.builder.\
    appName("test").\
    master("local[*]").\
    getOrCreate()

# 读取 hdfs 上的文件,注意:hdfs不能大写
df = spark.read.csv("hdfs:///data/studentInfo.txt",sep=",",header=False)\
    .toDF("id","name","age","gender","height") # 设置列名,否则用默认列名,不方便查询

print("----Schema-----")
df.printSchema() # 打印 字段类型Schema

# 通过 DataFrame API进行操作
df2 = df.select("name","age","gender","height").where("gender='男'")
df2.show()
spark.stop()

原文出处:/show_1IX3FULL5XBn.html