1. 程式人生 > >spark從入門到放棄三十三:Spark Sql(6)hive sql 案例 查詢分數大於80分的同學

spark從入門到放棄三十三:Spark Sql(6)hive sql 案例 查詢分數大於80分的同學

DROP TABLE IF EXISTS student_info"); sqlContext.sql("CREATE TABLE IF NOT EXISTS student_info (name STRING ,age INT)"); System.out.println("============================create table success"); //將學生的基本資訊匯入到StudentInfo 表 sqlContext.sql("LOAD DATA LOCAL INPATH '/data/hive/student_info/student_info.txt'
INTO TABLE student_info"); sqlContext.sql("DROP TABLE IF EXISTS student_scores"); sqlContext.sql("CREATE TABLE IF NOT EXISTS student_scores (name STRING ,score INT)"); //將學生的基本分數匯入到StudentInfo 表 sqlContext.sql("LOAD DATA LOCAL INPATH '/data/hive/student_info/student_scores.txt'
INTO TABLE student_scores"); //第二個功能接著將sql 返回的DataFrame 用於查詢 //執行sql 關聯兩張表查詢大於80分的學生 Dataset goodStudentDS=sqlContext.sql("SELECT ss.name ,s1.age,ss.score from student_info s1 JOIN student_scores ss ON s1.name=ss.name WHERE ss.score>=80"); //第三個功能,可以將 DataFrame 中的資料 理論上來說DataFrame 對應的RDD 資料 是ROW 即可 //將DataFrame 儲存到Hive 表中· // 接著將資料儲存到good_student_info 中 sqlContext.sql("
DROP TABLE IF EXISTS good_student_info"); System.out.println("create table success"); goodStudentDS.write().saveAsTable("good_student_info"); // 第四個功能 針對 good_student_info 表 直接建立 DataSet Dataset<Row> goodStudentDSRows=sqlContext.tables("good_student_info"); Row[] goodStudentRows=goodStudentDSRows.collect(); for (Row goodStudentRow:goodStudentRows){ System.out.println(goodStudentRow); } System.out.println(goodStudentRows); sc.close(); } }