【四】Spark SQL中SQLContext的使用(从json文件中加载数据)

SQLContext是Spark1.X中Spark SQL的入口点。

项目目录

【四】Spark SQL中SQLContext的使用(从json文件中加载数据)_第1张图片

pom.xml


  4.0.0
  com.sid.com
  sparksqltrain
  1.0-SNAPSHOT
  2008
  
    2.11.8
    2.2.0
  

  
    
      scala-tools.org
      Scala-Tools Maven2 Repository
      http://scala-tools.org/repo-releases
    
  

  
    
      scala-tools.org
      Scala-Tools Maven2 Repository
      http://scala-tools.org/repo-releases
    
  

  
    
    
      org.scala-lang
      scala-library
      ${scala.version}
    
    
    
      org.apache.spark
      spark-sql_2.11
      ${spark.version}
    

  

  
    src/main/scala
    src/test/scala
    
      
        org.scala-tools
        maven-scala-plugin
        
          
            
              compile
              testCompile
            
          
        
        
          ${scala.version}
          
            -target:jvm-1.5
          
        
      
      
        org.apache.maven.plugins
        maven-eclipse-plugin
        
          true
          
            ch.epfl.lamp.sdt.core.scalabuilder
          
          
            ch.epfl.lamp.sdt.core.scalanature
          
          
            org.eclipse.jdt.launching.JRE_CONTAINER
            ch.epfl.lamp.sdt.launching.SCALA_CONTAINER
          
        
      
    
  
  
    
      
        org.scala-tools
        maven-scala-plugin
        
          ${scala.version}
        
      
    
  

SQLContext.scala
package com.sid.com

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.SQLContext

/**
  * SQLContext的使用
  * */
object SQLContext {
  def main(args: Array[String]): Unit = {
    val path = args(0)
    //创建相应的Context
    val sparkConf = new SparkConf()
    sparkConf.setAppName("SQLContext").setMaster("local[3]")
    val sc = new SparkContext(sparkConf)
    val sqlContext = new SQLContext(sc);

    //处理json文件
    val people = sqlContext.read.format("json").load(path)
    people.printSchema()
    people.show()

    sc.stop()
  }
}

people.json

{"name":"zhangsan","age":30}
{"name":"lisi","age":31}
{"name":"wangwu","age":32}
{"name":"sid","age":32}

运行

【四】Spark SQL中SQLContext的使用(从json文件中加载数据)_第2张图片

【四】Spark SQL中SQLContext的使用(从json文件中加载数据)_第3张图片

【四】Spark SQL中SQLContext的使用(从json文件中加载数据)_第4张图片

你可能感兴趣的:(spark,SQL,Spark,SQL)