Spark Streaming(五):与Spark SQL整合

Spark Streaming最强大的地方在于,可以与Spark Core、Spark SQL整合使用,之前已经通过transform、foreachRDD等算子看到,如何将DStream中的RDD使用Spark Core执行批处理操作。现在就来看看,如何将DStream中的RDD与Spark SQL结合起来使用。

Demo:每隔10秒,统计最近60秒的,每个种类的每个商品的点击次数,然后统计出每个种类top3热门的商品。

package cn.spark.study.streaming;

import java.util.ArrayList;
import java.util.List;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.RowFactory;
import org.apache.spark.sql.hive.HiveContext;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaReceiverInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import scala.Tuple2;

/**
 * 与Spark SQL整合使用,top3热门商品实时统计
 */
public class Top3HotProduct {

    public static void main(String[] args) {
        SparkConf conf = new SparkConf()
                .setMaster("local[2]")
                .setAppName("Top3HotProduct");  
        JavaStreamingContext jssc = new JavaStreamingContext(conf, Durations.seconds(1));
        
        // 输入日志的格式
        // leo iphone mobile_phone
        
        // 首先,获取输入数据流               
        JavaReceiverInputDStream<String> productClickLogsDStream = jssc.socketTextStream("hadoop1", 9999);
        
        // 然后,应该是做一个映射,将每个种类的每个商品,映射为(category_product, 1)的这种格式
        // 从而在后面可以使用window操作,对窗口中的这种格式的数据,进行reduceByKey操作
        // 从而统计出来,一个窗口中的每个种类的每个商品的,点击次数
        JavaPairDStream<String, Integer> categoryProductPairsDStream = productClickLogsDStream
                .mapToPair(new PairFunction<String, String, Integer>() {

                    private static final long serialVersionUID = 1L;

                    @Override
                    public Tuple2<String, Integer> call(String productClickLog)
                            throws Exception {
                        String[] productClickLogSplited = productClickLog.split(" "); 
                        return new Tuple2<String, Integer>(productClickLogSplited[2] + "_" + 
                                productClickLogSplited[1], 1);
                    }
                    
                });
        
        // 然后执行window操作
        // 到这里,就可以做到,每隔10秒钟,对最近60秒的数据,执行reduceByKey操作
        // 计算出来这60秒内,每个种类的每个商品的点击次数
        JavaPairDStream<String, Integer> categoryProductCountsDStream = 
                categoryProductPairsDStream.reduceByKeyAndWindow(
                        
                        new Function2<Integer, Integer, Integer>() {

                            private static final long serialVersionUID = 1L;
                
                            @Override
                            public Integer call(Integer v1, Integer v2) throws Exception {
                                return v1 + v2;
                            }
                            
                        }, Durations.seconds(60), Durations.seconds(10));  
        
        // 然后针对60秒内的每个种类的每个商品的点击次数
        // foreachRDD,在内部,使用Spark SQL执行top3热门商品的统计
        categoryProductCountsDStream.foreachRDD(new Function<JavaPairRDD<String,Integer>, Void>() {
            
            private static final long serialVersionUID = 1L;

            @Override
            public Void call(JavaPairRDD<String, Integer> categoryProductCountsRDD) throws Exception {
                // 将该RDD,转换为JavaRDD<Row>的格式
                JavaRDD<Row> categoryProductCountRowRDD = categoryProductCountsRDD.map(
                        
                        new Function<Tuple2<String,Integer>, Row>() {

                            private static final long serialVersionUID = 1L;

                            @Override
                            public Row call(Tuple2<String, Integer> categoryProductCount)
                                    throws Exception {
                                String category = categoryProductCount._1.split("_")[0];
                                String product = categoryProductCount._1.split("_")[1];
                                Integer count = categoryProductCount._2;
                                return RowFactory.create(category, product, count);   
                            }
                            
                        });
                
                // 然后,执行DataFrame转换
                List<StructField> structFields = new ArrayList<StructField>();
                structFields.add(DataTypes.createStructField("category", DataTypes.StringType, true)); 
                structFields.add(DataTypes.createStructField("product", DataTypes.StringType, true));  
                structFields.add(DataTypes.createStructField("click_count", DataTypes.IntegerType, true));  
                StructType structType = DataTypes.createStructType(structFields);
                
                HiveContext hiveContext = new HiveContext(categoryProductCountsRDD.context());
                
                DataFrame categoryProductCountDF = hiveContext.createDataFrame(
                        categoryProductCountRowRDD, structType);
                
                // 将60秒内的每个种类的每个商品的点击次数的数据,注册为一个临时表
                categoryProductCountDF.registerTempTable("product_click_log");  
                
                // 执行SQL语句,针对临时表,统计出来每个种类下,点击次数排名前3的热门商品
                DataFrame top3ProductDF = hiveContext.sql(
                        "SELECT category,product,click_count "
                        + "FROM ("
                            + "SELECT "
                                + "category,"
                                + "product,"
                                + "click_count,"
                                + "row_number() OVER (PARTITION BY category ORDER BY click_count DESC) rank "
                            + "FROM product_click_log"  
                        + ") tmp "
                        + "WHERE rank<=3");
                

                // 接下来应该将数据保存到redis缓存、或者是mysql db中
                // 然后,配合一个J2EE系统,进行数据的展示和查询、图形报表
                
                top3ProductDF.show();      
                
                return null;
            }
            
        });
        
        jssc.start();
        jssc.awaitTermination();
        jssc.close();
    }   
}
package cn.spark.study.streaming

import org.apache.spark.SparkConf
import org.apache.spark.streaming.StreamingContext
import org.apache.spark.streaming.Seconds
import org.apache.spark.sql.Row
import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.types.StructField
import org.apache.spark.sql.types.StringType
import org.apache.spark.sql.types.IntegerType
import org.apache.spark.sql.hive.HiveContext


object Top3HotProduct {
  
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
        .setMaster("local[2]")  
        .setAppName("Top3HotProduct")
    val ssc = new StreamingContext(conf, Seconds(1))
    
    val productClickLogsDStream = ssc.socketTextStream("spark1", 9999)  
    val categoryProductPairsDStream = productClickLogsDStream
        .map { productClickLog => (productClickLog.split(" ")(2) + "_" + productClickLog.split(" ")(1), 1)}
    val categoryProductCountsDStream = categoryProductPairsDStream.reduceByKeyAndWindow(
        (v1: Int, v2: Int) => v1 + v2, 
        Seconds(60), 
        Seconds(10))  
    
    categoryProductCountsDStream.foreachRDD(categoryProductCountsRDD => {
      val categoryProductCountRowRDD = categoryProductCountsRDD.map(tuple => {
        val category = tuple._1.split("_")(0)
        val product = tuple._1.split("_")(1)  
        val count = tuple._2
        Row(category, product, count)  
      })
      
      val structType = StructType(Array(
          StructField("category", StringType, true),
          StructField("product", StringType, true),
          StructField("click_count", IntegerType, true)))
          
      val hiveContext = new HiveContext(categoryProductCountsRDD.context)
      
      val categoryProductCountDF = hiveContext.createDataFrame(categoryProductCountRowRDD, structType)  
      
      categoryProductCountDF.registerTempTable("product_click_log")  
      
      val top3ProductDF = hiveContext.sql(
            "SELECT category,product,click_count "
            + "FROM ("
              + "SELECT "
                + "category,"
                + "product,"
                + "click_count,"
                + "row_number() OVER (PARTITION BY category ORDER BY click_count DESC) rank "
              + "FROM product_click_log"  
            + ") tmp "
            + "WHERE rank<=3")
            
      top3ProductDF.show()
    })
    
    ssc.start()
    ssc.awaitTermination()
  } 
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,406评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,732评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,711评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,380评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,432评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,301评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,145评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,008评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,443评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,649评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,795评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,501评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,119评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,731评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,865评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,899评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,724评论 2 354

推荐阅读更多精彩内容