SparkCore高级01

一、RDD回顾

1、RDD分两个特性

 transformation: lazy

  map filter union flatMap mapPartition

 action: eager ==> Spark Job

  collect

  take

二、Spark开发-日志统计分析

1、创建scala工程、pom.xml文件引入hadoop、scala、spark依赖

2、需求

对日志文件分析,求每个域名的流量

3、需求分析

 (1)获取到日志中每条记录的域名和流量

   域名:字段11

   流量:字段20

    log => (11,20)


val lines = sc.textFile("C:\\Users\\dell\\Desktop\\LearningNote\\BigData\\bd.log")
lines.map(x =>{
  val temp = x.split("\t")
  (temp(10),temp(19))            
})

貌似可以在map里面结构化编程,最后那一行的值传递给map函数  

(2)按照域名进行分组

(3)分组求和


val lines = sc.textFile("C:\\Users\\dell\\Desktop\\LearningNote\\BigData\\bd.log")
lines.map(x =>{
  val temp = x.split("\t")
  (temp(10),temp(19).toLong)
}).reduceByKey(_ + _).foreach(println)

4、工业做法,捕捉有可能出现的数据溢出


val lines = sc.textFile("C:\\Users\\dell\\Desktop\\LearningNote\\BigData\\bd.log")
  lines.map(x => {
  val temp = x.split("\t")
  var traffic = 0L
  try{
    traffic = temp(19).toLong
  }catch{
    case e:Exception => traffic = 0L
  }
    (temp(10),traffic)
}).reduceByKey(_ + _).foreach(println)

二、需求

1、求每个省份的访问次数的TOPN

2、需求分析:

(1)获取id

(2)(省份,1)

(3)reduceByKey(_ + _)

(4)排序sortBy方法,可以对集合中一个或多个属性进行排序


sortBy(_._2,false)
lines.map(x => {
  val temp = x.split("\t")
  (IpUtils.getProvince(temp(6)),1)
}).reduceByKey(_ + _).sortBy(_._2,false)

三、需求   

1、需求分析

需求3:求每个域名下访问数最多的文件资源

(1)先把文件资源拿到

(2)文件资源格式:user_upload/153106401119141606a90cc5475b6eb86a142c0ced86b

(3)((域名,资源),次数)

(4)分组group by(域名,(域名,资源),次数)


/*
     *需求3:求每个域名下访问数最多的文件资源
   * (1)先把文件资源拿到
   *     文件资源在第13个字段(12)http://v1.go2yd.com/user_upload/153106401119141606a90cc5475b6eb86a142c0ced86b.mp4_bd.mp4
   * (2)文件资源格式:user_upload/153106401119141606a90cc5475b6eb86a142c0ced86b
   * (3)((域名,资源),次数)
    *(4)分组group by(域名,(域名,资源),次数)
*/
    lines.map(x =>{
      val temp = x.split("\t")
      ((temp(10),getPath(temp(12))),1)
    })
      //((域名,资源),次数)
      .reduceByKey(_ + _)
      //分组:域名下,每个文件资源访问次数
      //如此表达:域名,(域名,资源),次数)  groupBy(_._1._1)以域名为一组,其余的参数又一组形成新map
      .groupBy(_._1._1).
      //将((域名,资源),次数)转为list,再对次数排序
      //思考:为什么不可以直接sortBy(_._2),因为这样就不能把同域名的放在排序的条件中了,而是全部结果排序
      mapValues(_.toList.sortBy(_._2).reverse).map(_._2)
        .collect().foreach(println)
 
package com.HBinz.spark.core

object PathTest {
def main(args: Array[String]): Unit = {
val url = "http://v1.go2yd.com/user_upload/153106401119141606a90cc5475b6eb86a142c0ced86b.mp4_bd.mp4"
println(getPath(url))
}

def getPath(url: String) = {
//将字符串//去掉
//http:v1.go2yd.com/user_upload/153106401119141606a90cc5475b6eb86a142c0ced86b.mp4_bd.mp4
val pathTemp = url.replaceFirst("//", "")
//我们要截取的是/user_upload/153106401119141606a90cc5475b6eb86a142c0ced86b.mp4_bd.mp4
//所以我们找到/是第几个字符串
val pathIndex = pathTemp.indexOf("/")
//排除错误的情况,使用字符串拼接,只取pathTemp第pathIndex之后的字符串
var path = ""
if (pathIndex != -1) {
path = pathTemp.substring(pathIndex)
}
path
}
}

作业:

求访问次数最多的资源文件。

研究一下窗口函数!!!

猜你喜欢

转载自blog.csdn.net/Binbinhb/article/details/88553211