mysql - 如何使用 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 解析器
解决方案
有没有为 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.sql
,Dataset.selectExpr
或简单的expr
标准函数。您也可以直接使用 SQL 解析器。
无耻插件你可能想阅读Mastering Spark SQL 一书中的ParserInterface — SQL Parser Contract 。
推荐阅读
- python - Pandas 通过多列和键排序
- flutter - 如何将提供者类名作为参数传递?
- flutter - 如何在颤动的图像中制作这个选择器
- javascript - Chrome contenteditable 在文本节点开头设置插入符号不起作用
- python - 矩形棱柱旋转后求顶点的方程
- python - 遍历 dict 并将值分配给列表
- java - 无法为共享消费者组的各种 KafkaConsumer 实例获取分区
- r - 为什么当我单击任何脚注的上标时,它会将我带到文档的第一页而不是脚注?
- python-3.x - 熊猫申请 - 做同样的事情却有不同的结果?
- java - 解析嵌套 json 和更改响应结构时遇到问题