spark&hive--练习2

需求:

在hive中创建对应表,并且导入数据,使用spark完成对应的查询

stu_name course score

张三 语文 98

张三 数学 95

张三 英语 89

李四 语文 97

李四 数学 88

李四 英语 90

1.hive建表语句,导入数据语句,从linux文件系统导入

2.使用sparksql查询上述表,期望结果如下,并且将计算结果添加到mysql

name 语文 数学 英语

张三 98 95 89

李四 97 88 90

1.hive建表语句,导入数据语句,从linux文件系统导入

sql 复制代码
create table student(
   stu_name   string,
   course     string,
   score      int
)
row format delimited
fields terminated by ',';

load data local inpath '/root/stu.txt' into table student;

select * from default.student;

2.使用sparksql查询上述表,期望结果如下,并且将计算结果添加到mysql

【注:表名前边加上数据库。如:default.student】

python 复制代码
from pyspark.sql import SparkSession

if __name__ == '__main__':
    spark = SparkSession.builder \
        .appName("测试") \
        .config("hive.metastore.uris", 'thrift://hadoop11:9083') \
        .enableHiveSupport() \
        .getOrCreate()


    df = spark.sql("""
        select stu_name,
               max(case when course='语文' then score else null end) chinese,
               max(case when course='数学' then score else null end) math,
               max(case when course='英语' then score else null end) english
        from default.student
        group by stu_name
    """)

    props = {'user': 'root', 'password': '123456', 'driver': 'com.mysql.jdbc.Driver'}
    df.write.jdbc(url='jdbc:mysql://hadoop11:3306/test1', table='df_student', properties=props)

    spark.stop()

sql结果:

相关推荐
databook13 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室14 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三15 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271119 小时前
Python之语言特点
python
阿里云大数据AI技术19 小时前
StarRocks 助力数禾科技构建实时数仓:从数据孤岛到智能决策
大数据
刘立军19 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
Lx3521 天前
Hadoop数据处理优化:减少Shuffle阶段的性能损耗
大数据·hadoop
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django