首页 > 解决方案 > 如何使用 Spark 从 .sql 转储中提取包含数据的表?

问题描述

我有大约四个 *.sql 独立转储(每个大约 20GB),我需要将它们转换为 Apache Spark 中的数据集。

我尝试使用 InnoDB 安装和制作本地数据库并导入转储,但这似乎太慢了(花了大约 10 个小时)

我使用直接将文件读入火花

import org.apache.spark.sql.SparkSession

var sparkSession = SparkSession.builder().appName("sparkSession").getOrCreate()
var myQueryFile = sc.textFile("C:/Users/some_db.sql")

//Convert this to indexed dataframe so you can parse multiple line create / data statements. 
//This will also show you the structure of the sql dump for your usecase.

var myQueryFileDF = myQueryFile.toDF.withColumn("index",monotonically_increasing_id()).withColumnRenamed("value","text") 


// Identify all tables and data in the sql dump along with their indexes

var tableStructures = myQueryFileDF.filter(col("text").contains("CREATE TABLE"))
var tableStructureEnds = myQueryFileDF.filter(col("text").contains(") ENGINE"))

println(" If there is a count mismatch between these values choose different substring "+ tableStructures.count()+ " " + tableStructureEnds.count())

var tableData = myQueryFileDF.filter(col("text").contains("INSERT INTO "))

问题是转储包含多个表,每个表都需要成为数据集。为此,我需要了解我们是否可以为一张桌子做到这一点。有没有为 scala spark 编写的 .sql 解析器?

有没有更快的方法呢?我可以将它从 .sql 自包含文件中直接读入 hive 吗?

更新 1:我正在根据 Ajay 给出的输入为此编写解析器

更新 2:将所有内容更改为基于数据集的代码以按照建议使用 SQL 解析器

标签: mysqlscalaapache-spark

解决方案


有没有为 scala spark 编写的 .sql 解析器?

是的,有一个,你似乎已经在使用它了。这就是 Spark SQL 本身!惊讶吗?

SQL 解析器接口 ( ParserInterface) 可以从 SQL 语句的文本表示创建关系实体。这几乎就是你的情况,不是吗?

请注意,ParserInterface一次只处理一条 SQL 语句,因此您必须以某种方式解析整个转储并找到表定义和行。

从. ParserInterface_ sqlParser_SessionState

scala> :type spark
org.apache.spark.sql.SparkSession

scala> :type spark.sessionState.sqlParser
org.apache.spark.sql.catalyst.parser.ParserInterface

Spark SQL 附带了几种方法,这些方法提供了接口的入口点,例如SparkSession.sqlDataset.selectExpr或简单的expr标准函数。您也可以直接使用 SQL 解析器。


无耻插件你可能想阅读Mastering Spark SQL 一书中的ParserInterface — SQL Parser Contract 。


推荐阅读