创建dataframe的几种方式——读取json格式的文件

创建DataFrame的方式一共有

  1. 读取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()

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值