创建DataFrame的方式一共有
- 读取json格式的文件创建DataFrame
注意:
- json文件中的json数据不能嵌套json格式数据。
- DataFrame是一个一个Row类型的RDD,df.rdd()/df.javaRdd()。
- 可以两种方式读取json格式的文件。
- df.show()默认显示前20行数据。
- DataFrame原生API可以操作DataFrame(不方便)。
- 注册成临时表时,表中的列默认按ascii顺序显示列。
一、Java版本的代码:
SparkConf conf = new SparkConf();
conf.setMaster("local").setAppName("jsonfile");
SparkContext sc = new SparkContext(conf);
//创建sqlContext
SQLContext sqlContext = new SQLContext(sc);
/**
* DataFrame的底层是一个一个的RDD RDD的泛型是Row类型。
* 以下两种方式都可以读取json格式的文件
*/
DataFrame df = sqlContext.read().format("json").load("sparksql/json");
// DataFrame df2 = sqlContext.read().json("sparksql/json.txt");
// df2.show();
/**
* DataFrame转换成RDD
*/
RDD<Row> rdd = df.rdd();
/**
* 显示 DataFrame中的内容,默认显示前20行。如果现实多行要指定多少行show(行数)
* 注意:当有多个列时,显示的列先后顺序是按列的ascii码先后显示。
*/
// df.show();
/**
* 树形的形式显示schema信息
*/
df.printSchema();
/**
* dataFram自带的API 操作DataFrame
*/
//select name from table
// df.select("name").show();
//select name age+10 as addage from table
df.select(df.col("name"),df.col("age").plus(10).alias("addage")).show();
//select name ,age from table where age>19
df.select(df.col("name"),df.col("age")).where(df.col("age").gt(19)).show();
//select count(*) from table group by age
df.groupBy(df.col("age")).count().show();
/**
* 将DataFrame注册成临时的一张表,这张表临时注册到内存中,是逻辑上的表,不会雾化到磁盘
*/
df.registerTempTable("jtable");
DataFrame sql = sqlContext.sql("select age,count(1) from jtable group by age");
DataFrame sql2 = sqlContext.sql("select * from jtable");
sc.stop();
默认情况下显示前20行,如果要想显示多行,那么可以通过设置的方式。
读取json格式文件的方式有两种:
DataFrame df = sqlContext.read().format("json").load("sparksql/json");
// DataFrame df2 = sqlContext.read().json("sparksql/json.txt");
显示表信息的方式有两种:
df.show或者df.printSchema
二、Scala代码
val conf = new SparkConf()
conf.setMaster("local").setAppName("jsonfile")
val sc = new SparkContext(conf)
val sqlContext = new SQLContext(sc)
val df = sqlContext.read.json("sparksql/json")
//val df1 = sqlContext.read.format("json").load("sparksql/json")
df.show()
df.printSchema()
//select * from table
df.select(df.col("name")).show()
//select name from table where age>19
df.select(df.col("name"),df.col("age")).where(df.col("age").gt(19)).show()
//select count(*) from table group by age
df.groupBy(df.col("age")).count().show();
/**
* 注册临时表
*/
df.registerTempTable("jtable")
val result = sqlContext.sql("select * from jtable")
result.show()
sc.stop()