Spark SQL数据加载和保存实例讲解
一、前置知识详解
spark sql重要是操作dataframe,dataframe本身提供了save和load的操作,
load:可以创建dataframe,
save:把dataframe中的数据保存到文件或者说与具体的格式来指明我们要读取的文件的类型以及与具体的格式来指出我们要输出的文件是什么类型。
二、spark sql读写数据代码实战
import org.apache.spark.sparkconf; import org.apache.spark.api.java.javardd; import org.apache.spark.api.java.javasparkcontext; import org.apache.spark.api.java.function.function; import org.apache.spark.sql.*; import org.apache.spark.sql.types.datatypes; import org.apache.spark.sql.types.structfield; import org.apache.spark.sql.types.structtype; import java.util.arraylist; import java.util.list; public class sparksqlloadsaveops { public static void main(string[] args) { sparkconf conf = new sparkconf().setmaster("local").setappname("sparksqlloadsaveops"); javasparkcontext sc = new javasparkcontext(conf); sqlcontext = new sqlcontext(sc); /** * read()是dataframereader类型,load可以将数据读取出来 */ dataframe peopledf = sqlcontext.read().format("json").load("e:\\spark\\sparkinstanll_package\\big_data_software\\spark-1.6.0-bin-hadoop2.6\\examples\\src\\main\\resources\\people.json"); /** * 直接对dataframe进行操作 * json: 是一种自解释的格式,读取json的时候怎么判断其是什么格式? * 通过扫描整个json。扫描之后才会知道元数据 */ //通过mode来指定输出文件的是append。创建新文件来追加文件 peopledf.select("name").write().mode(savemode.append).save("e:\\personnames"); } }
读取过程源码分析如下:
1. read方法返回dataframereader,用于读取数据。
/** * :: experimental :: * returns a [[dataframereader]] that can be used to read data in as a [[dataframe]]. * {{{ * sqlcontext.read.parquet("/path/to/file.parquet") * sqlcontext.read.schema(schema).json("/path/to/file.json") * }}} * * @group genericdata * @since 1.4.0 */ @experimental //创建dataframereader实例,获得了dataframereader引用 def read: dataframereader = new dataframereader(this)
2. 然后再调用dataframereader类中的format,指出读取文件的格式。
/** * specifies the input data source format. * * @since 1.4.0 */ def format(source: string): dataframereader = { this.source = source this }
3. 通过dtaframereader中load方法通过路径把传入过来的输入变成dataframe。
/** * loads input in as a [[dataframe]], for data sources that require a path (e.g. data backed by * a local or distributed file system). * * @since 1.4.0 */ // todo: remove this one in spark 2.0. def load(path: string): dataframe = { option("path", path).load() }
至此,数据的读取工作就完成了,下面就对dataframe进行操作。
下面就是写操作!!!
1. 调用dataframe中select函数进行对列筛选
/** * selects a set of columns. this is a variant of `select` that can only select * existing columns using column names (i.e. cannot construct expressions). * * {{{ * // the following two are equivalent: * df.select("cola", "colb") * df.select($"cola", $"colb") * }}} * @group dfops * @since 1.3.0 */ @scala.annotation.varargs def select(col: string, cols: string*): dataframe = select((col +: cols).map(column(_)) : _*)
2. 然后通过write将结果写入到外部存储系统中。
/** * :: experimental :: * interface for saving the content of the [[dataframe]] out into external storage. * * @group output * @since 1.4.0 */ @experimental def write: dataframewriter = new dataframewriter(this)
3. 在保持文件的时候mode指定追加文件的方式
/** * specifies the behavior when data or table already exists. options include: // overwrite是覆盖 * - `savemode.overwrite`: overwrite the existing data. //创建新的文件,然后追加 * - `savemode.append`: append the data. * - `savemode.ignore`: ignore the operation (i.e. no-op). * - `savemode.errorifexists`: default option, throw an exception at runtime. * * @since 1.4.0 */ def mode(savemode: savemode): dataframewriter = { this.mode = savemode this }
4. 最后,save()方法触发action,将文件输出到指定文件中。
/** * saves the content of the [[dataframe]] at the specified path. * * @since 1.4.0 */ def save(path: string): unit = { this.extraoptions += ("path" -> path) save() }
三、spark sql读写整个流程图如下
四、对于流程中部分函数源码详解
dataframereader.load()
1. load()返回dataframe类型的数据集合,使用的数据是从默认的路径读取。
/** * returns the dataset stored at path as a dataframe, * using the default data source configured by spark.sql.sources.default. * * @group genericdata * @deprecated as of 1.4.0, replaced by `read().load(path)`. this will be removed in spark 2.0. */ @deprecated("use read.load(path). this will be removed in spark 2.0.", "1.4.0") def load(path: string): dataframe = { //此时的read就是dataframereader read.load(path) }
2. 追踪load源码进去,源码如下:
在dataframereader中的方法。load()通过路径把输入传进来变成一个dataframe。
/** * loads input in as a [[dataframe]], for data sources that require a path (e.g. data backed by * a local or distributed file system). * * @since 1.4.0 */ // todo: remove this one in spark 2.0. def load(path: string): dataframe = { option("path", path).load() }
3. 追踪load源码如下:
/** * loads input in as a [[dataframe]], for data sources that don't require a path (e.g. external * key-value stores). * * @since 1.4.0 */ def load(): dataframe = { //对传入的source进行解析 val resolved = resolveddatasource( sqlcontext, userspecifiedschema = userspecifiedschema, partitioncolumns = array.empty[string], provider = source, options = extraoptions.tomap) dataframe(sqlcontext, logicalrelation(resolved.relation)) }
dataframereader.format()
1. format:具体指定文件格式,这就获得一个巨大的启示是:如果是json文件格式可以保持为parquet等此类操作。
spark sql在读取文件的时候可以指定读取文件的类型。例如,json,parquet.
/** * specifies the input data source format.built-in options include “parquet”,”json”,etc. * * @since 1.4.0 */ def format(source: string): dataframereader = { this.source = source //filetype this }
dataframe.write()
1. 创建dataframewriter实例
/** * :: experimental :: * interface for saving the content of the [[dataframe]] out into external storage. * * @group output * @since 1.4.0 */ @experimental def write: dataframewriter = new dataframewriter(this) 1
2. 追踪dataframewriter源码如下:
以dataframe的方式向外部存储系统中写入数据。
/** * :: experimental :: * interface used to write a [[dataframe]] to external storage systems (e.g. file systems, * key-value stores, etc). use [[dataframe.write]] to access this. * * @since 1.4.0 */ @experimental final class dataframewriter private[sql](df: dataframe) {
dataframewriter.mode()
1. overwrite是覆盖,之前写的数据全都被覆盖了。
append:是追加,对于普通文件是在一个文件中进行追加,但是对于parquet格式的文件则创建新的文件进行追加。
/** * specifies the behavior when data or table already exists. options include: * - `savemode.overwrite`: overwrite the existing data. * - `savemode.append`: append the data. * - `savemode.ignore`: ignore the operation (i.e. no-op). //默认操作 * - `savemode.errorifexists`: default option, throw an exception at runtime. * * @since 1.4.0 */ def mode(savemode: savemode): dataframewriter = { this.mode = savemode this }
2. 通过模式匹配接收外部参数
/** * specifies the behavior when data or table already exists. options include: * - `overwrite`: overwrite the existing data. * - `append`: append the data. * - `ignore`: ignore the operation (i.e. no-op). * - `error`: default option, throw an exception at runtime. * * @since 1.4.0 */ def mode(savemode: string): dataframewriter = { this.mode = savemode.tolowercase match { case "overwrite" => savemode.overwrite case "append" => savemode.append case "ignore" => savemode.ignore case "error" | "default" => savemode.errorifexists case _ => throw new illegalargumentexception(s"unknown save mode: $savemode. " + "accepted modes are 'overwrite', 'append', 'ignore', 'error'.") } this }
dataframewriter.save()
1. save将结果保存传入的路径。
/** * saves the content of the [[dataframe]] at the specified path. * * @since 1.4.0 */ def save(path: string): unit = { this.extraoptions += ("path" -> path) save() }
2. 追踪save方法。
/** * saves the content of the [[dataframe]] as the specified table. * * @since 1.4.0 */ def save(): unit = { resolveddatasource( df.sqlcontext, source, partitioningcolumns.map(_.toarray).getorelse(array.empty[string]), mode, extraoptions.tomap, df) }
3. 其中source是sqlconf的defaultdatasourcename
private var source: string = df.sqlcontext.conf.defaultdatasourcename
其中default_data_source_name默认参数是parquet。
// this is used to set the default data source val default_data_source_name = stringconf("spark.sql.sources.default", defaultvalue = some("org.apache.spark.sql.parquet"), doc = "the default data source to use in input/output.")
dataframe.scala中部分函数详解:
1. todf函数是将rdd转换成dataframe
/** * returns the object itself. * @group basic * @since 1.3.0 */ // this is declared with parentheses to prevent the scala compiler from treating // `rdd.todf("1")` as invoking this todf and then apply on the returned dataframe. def todf(): dataframe = this
2. show()方法:将结果显示出来
/** * displays the [[dataframe]] in a tabular form. for example: * {{{ * year month avg('adj close) max('adj close) * 1980 12 0.503218 0.595103 * 1981 01 0.523289 0.570307 * 1982 02 0.436504 0.475256 * 1983 03 0.410516 0.442194 * 1984 04 0.450090 0.483521 * }}} * @param numrows number of rows to show * @param truncate whether truncate long strings. if true, strings more than 20 characters will * be truncated and all cells will be aligned right * * @group action * @since 1.5.0 */ // scalastyle:off println def show(numrows: int, truncate: boolean): unit = println(showstring(numrows, truncate)) // scalastyle:on println
追踪showstring源码如下:showstring中触发action收集数据。
/** * compose the string representing rows for output * @param _numrows number of rows to show * @param truncate whether truncate long strings and align cells right */ private[sql] def showstring(_numrows: int, truncate: boolean = true): string = { val numrows = _numrows.max(0) val sb = new stringbuilder val takeresult = take(numrows + 1) val hasmoredata = takeresult.length > numrows val data = takeresult.take(numrows) val numcols = schema.fieldnames.length
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。