案例: 查詢某地的人口數量與平均年齡;
分析:使用Spark查詢人口的數量和平均年齡,首先我們使用Spark SQL 方式查詢,將原始數據讀入,將其轉化爲DATAFRAME,然後是SQL方式計算:
準備實驗數據代碼如下:
object demo { def main(args: Array[String]): Unit = { val write = new FileWriter("e://data.txt",false) val rand = new Random() for (i <- 1 to 1000){ write.write(i + " " + rand.nextInt(100)) write.write(System.getProperty("line.separator")) } write.flush() write.close() } }
2.創建Spark SQL 查詢平均年齡
Counts { main(args: Array[]): Unit = { conf = SparkConf().setAppName().setMaster() sc = SparkContext(conf) sparkSession = SparkSession.().getOrCreate() schema = ( (, IntegerType, ) :: (, IntegerType, ) :: ) people = sc.textFile().map( _.split()).map(p => (p().trim.toInt, p().trim.toInt)) dataFrame = sparkSession.createDataFrame(people, schema) dataFrame.printSchema() dataFrame.createOrReplaceTempView() sparkSession.sql().show() } }
3.創建Spark SQL 查詢平均人口總數
Counts { main(args: Array[]): Unit = { conf = SparkConf().setAppName().setMaster() sc = SparkContext(conf) sparkSession = SparkSession.().getOrCreate() schema = ( (, IntegerType, ) :: (, IntegerType, ) :: ) people = sc.textFile().map( _.split()).map(p => (p().trim.toInt, p().trim.toInt)) dataFrame = sparkSession.createDataFrame(people, schema) dataFrame.printSchema() dataFrame.createOrReplaceTempView() sparkSession.sql().show() } }
總結:在讀入數據使用Spark SQL 計算是首先需要知道數據的的結構類型,然後創建相應的數據結構。讀入數據將其轉換爲DATAFRAME。在計算之前可以將數據打印一部分出來看看。