Spark DataFrame查询操作

题目

  1. 进入spark-shell
  2. 保存的Json文件载入到DataFrame
  3. 执行DataFrame中的查询(以下查询分别用转换操作算子和SQL语句实现),并用show命令打印出摘要信息
    ① 查询单价小于0.2的所有商品
    ② 查询订单551845~551850的顾客
    ③ 统计本数据中包含了多少个订单
    ④ 统计所有订单的最大金额、订单包含的最多产品数量、订单包含的最多产品种类

实验结果

利用Spark 转换操作算子查询

保存的Json文件载入到DataFrame

路径:“file:///root/sql_out/out.json” 是自己的

var df = spark.read.format("json").load("file:///root/sql_out/out.json")

1.1

查询单价小于0.2的所有商品

df.select("Description","UnitPrice").where("UnitPrice<0.2 and UnitPrice>0").show

1.2

查询订单551845~551850的顾客

df.select("CustomerID","InvoiceNo").where("InvoiceNo>=551845 and InvoiceNo <=551850").show

1.3

统计本数据中包含了多少个订单

val sum = df.select("InvoiceNo").groupBy("InvoiceNo").count()
sum.describe("count").show

1.4

统计所有订单的最大金额

val res1 = df.select("InvoiceNo","UnitPrice","Quantity").withColumn("sum",col("UnitPrice")*col("Quantity"))
res1.groupBy("InvoiceNo").sum("sum").orderBy(desc("sum(sum)")).show

1.5

订单包含的最多产品数量

val res2 = df.select("InvoiceNo","Quantity").groupBy("InvoiceNo").sum("Quantity")
res2.orderBy(desc("sum(Quantity)")).show

1.6

订单包含的最多产品种类

df.select("InvoiceNo","Description").distinct().groupBy("InvoiceNo").count().orderBy(desc("count")).show

1.7

利用DataFrame的SQL语句实现查询

保存的文件Json载入到DataFrame

var df = spark.read.format("json").load("file:///root/sql_out/out.json")
df.createTempView("A")

查询单价小于0.2的所有商品

df.sqlContext.sql("select Description,UnitPrice from A where UnitPrice<0.2 and UnitPrice>0").show

查询订单551845~551850的顾客

df.sqlContext.sql("select CustomerID,InvoiceNo from A where InvoiceNo>=551845 and InvoiceNo <=551850").show

统计本数据中包含了多少个订单

df.sqlContext.sql("select count(*) from (select InvoiceNo,count(*) from A group by InvoiceNo) t").show

统计所有订单的最大金额

df.sqlContext.sql("select InvoiceNo, sum(UnitPrice*Quantity) as sum from A group by InvoiceNo order by sum desc").show

订单包含的最多产品数量

df.sqlContext.sql("select InvoiceNo, sum(Quantity) as count from A group by InvoiceNo order by count desc").show

订单包含的最多产品种类

df.sqlContext.sql("select InvoiceNo, count(distinct Description) as type from A group by InvoiceNo order by type desc").show

关于Spark转换操作算子参考资料

spark dataframe操作集锦(提取前几行,合并,入库等)
spark对DataFrame操作的方法(包含去除重复)

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值