Spark SQL数据加载和保存实战

http://www.cnblogs.com/whyhappy/p/6740928.html

一:前置知识详解: 
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,用于读取数据。

复制代码
[[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)
复制代码
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
复制代码

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 可以使用Spark SQL连接MongoDB,对数据进行统计分析,然后将结果保存到MySQL中。 具体步骤如下: 1. 首先,需要在Spark中引入MongoDB的驱动程序,可以使用以下代码: ``` spark-shell --packages org.mongodb.spark:mongo-spark-connector_2.11:2.4.1 ``` 2. 然后,使用Spark SQL连接MongoDB,读取数据并进行统计分析,可以使用以下代码: ``` val df = spark.read.format("com.mongodb.spark.sql.DefaultSource") .option("uri", "mongodb://localhost/test.coll") .load() df.createOrReplaceTempView("data") val result = spark.sql("SELECT COUNT(*) FROM data WHERE age > 20") result.show() ``` 3. 最后,将结果保存到MySQL中,可以使用以下代码: ``` result.write.format("jdbc") .option("url", "jdbc:mysql://localhost:3306/test") .option("dbtable", "result") .option("user", "root") .option("password", "password") .save() ``` 其中,url、dbtable、user和password需要根据实际情况进行修改。 以上就是使用Spark SQL连接MongoDB,对数据进行统计分析,并将结果保存到MySQL中的步骤。 ### 回答2: MongoDB是一种NoSQL数据库,而Spark是一种分布式计算框架。它们可以协同工作,以便在处理大规模数据时提高效率和速度。但是,在将MongoDB数据转化为Spark SQL进行统计分析之后,我们可能需要将数据保存到MySQL数据库中。下面是如何使用Spark SQL和Scala将MongoDB数据转化为并保存到MySQL数据库中。 首先,我们需要使用MongoDB的Spark Connector连接MongoDB。在使用Spark Shell进行连接时,我们需要使用以下命令导入依赖项: ``` import com.mongodb.spark._ import org.apache.spark.sql._ ``` 然后,我们可以使用以下代码连接到MongoDB数据库: ``` val spark = SparkSession.builder() .appName("MongoDB with SparkSQL") .master("local[*]") .config("spark.mongodb.input.uri", "mongodb://localhost/test.myCollection") .config("spark.mongodb.output.uri", "mongodb://localhost/test.outCollection") .getOrCreate() val df = spark.read.mongo() ``` 这将返回一个DataFrame,我们可以使用Spark SQL进行数据分析和处理。例如,我们可以使用以下代码对数据进行聚合: ``` val aggregationResultDF = df.groupBy("field1").agg(sum("field2")) ``` 出于安全考虑,我们可以在保存到MySQL之前对数据进行清洗和转换。然后,我们可以使用以下代码将结果保存到MySQL: ``` val mysqlConnectionProperties = new Properties() mysqlConnectionProperties.setProperty("user", "root") mysqlConnectionProperties.setProperty("password", "123456") mysqlConnectionProperties.setProperty("driver", "com.mysql.jdbc.Driver") aggregationResultDF.write.mode("append").jdbc("jdbc:mysql://localhost/db", "table", mysqlConnectionProperties) ``` 这将把结果保存到名为“table”的MySQL表中。 总之,使用Spark SQL和Scala将MongoDB数据转化为并保存到MySQL数据库中是相对容易的。我们只需连接到MongoDB数据库,将其转换为DataFrame,聚合和处理数据,然后将结果写入MySQL。这可以为我们提供一个强大的数据处理工具,可用于处理大量数据并进行大规模分析。 ### 回答3: MongoDB是一个基于文档的非关系型数据库系统,而Spark SQL是一个基于Spark的模块,可以通过其数据源API轻松访问各种结构化数据源,包括MongoDB数据库。Mysql则是一个高度可扩展的关系型数据库管理系统,广泛用于Web应用程序中。为了将MongoDB中的数据统计并保存到Mysql中,我们可以使用MongoDB-Spark Connector和MySQL Connector for Java。 MongoDB-Spark Connector使我们可以轻松地将MongoDB集合转换为DataFrame数据结构,使我们可以随意使用Spark SQL的各种高级特性和功能来处理MongoDB的数据。可以使用MongoDB-Spark Connector建立连接,并使用其提供的API来读取MongoDB中的数据。例如,以下代码将创建一个名为“students”的DataFrame,其中包含MongoDB中具有“name”和“age”字段的所有记录: ``` val students = spark.read.format("com.mongodb.spark.sql.DefaultSource").option("uri","mongodb://localhost/test.students").load() ``` 接下来,我们可以使用Spark SQL来对这些数据进行各种统计操作和计算。例如,以下命令将计算姓名为“Tom”的学生的平均年龄: ``` import org.apache.spark.sql.functions._ students.filter($"name" === "Tom").agg(avg("age")) ``` 一旦我们完成了Spark SQL中的统计和计算过程,我们需要将结果保存到Mysql数据库中。为此,我们可以使用Mysql Connector for Java建立连接,并使用其提供的API将数据写入Mysql数据库。以下代码展示了如何使用Mysql Connector for Java来将数据框中的数据写入名为“results”的表中: ``` val properties = new Properties() properties.put("user", "root") // MySQL用户名 properties.put("password", "root") // MySQL登录密码 result.write.mode("append").jdbc("jdbc:mysql://localhost/test", "results", properties) ``` 此外,我们还可以使用Spark的Parallelize功能将结果保存到HDFS等分布式文件系统中。 总之,在将MongoDB中的数据统计并保存到Mysql中的整个过程中,我们可以利用Spark SQL和相关的连接器库(MongoDB-Spark Connector和MySQL Connector for Java)来快速方便地实现,从而提高大规模数据处理的效率和精度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值