spark从入门到放弃三十五:Spark Sql(8)根据日志统计用户UV

文章地址:http://www.haha174.top/article/details/252965
在实际的工作中,根据用户的行为日志进行统计分析是一件很常见的事情,下面给出一个小例子,根据用户的行为日志分析用户访问次数。

object DailyUV {
  def main(args: Array[String]): Unit = {
    val conf=new SparkConf().setAppName("DailyUV").setMaster("local")
    val  sc = new SparkContext(conf)
    val sqlContext = new SQLContext(sc)
    //1  模拟用户行为日志  第一列是时间,第二列是用户id
    val userAccessLog=Array(
      "2015-10-01,1122",
      "2015-10-01,1122",
      "2015-10-01,1123",
      "2015-10-01,1124",
      "2015-10-02,1121",
      "2015-10-02,1122",
      "2015-10-01,1123",
      "2015-10-01,1124");
    //2  创建RDD
    val userAccessLogRDD=sc.parallelize(userAccessLog,5);
    //3 将RDD  转换为DataSet 首先转换元素为Row 的RDD
    val userAccessLogRowRDD=userAccessLogRDD.map(log=>{
      Row(log.split(",")(0),log.split(",")(1).toInt)
    })
    //然后构造DataSet元数据
    val structType=StructType(Array(
      DataTypes.createStructField("date", DataTypes.StringType, true),
      DataTypes.createStructField("userId", DataTypes.IntegerType, true)
    ))
    //使用sqlContext  创建DataSet
    import sqlContext.implicits. _
    val userAccessLogRowDS=sqlContext.createDataFrame( userAccessLogRowRDD,structType);
    userAccessLogRowDS.groupBy("date")
      .agg('date,countDistinct('userId),count('userId))//DataSet<Row>
      .show()

    userAccessLogRowDS.show()
  }
}

运行结果
这里写图片描述

欢迎关注,更多惊喜等着你

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值