【发布时间】:2021-11-25 18:34:33
【问题描述】:
我有一个 spark 数据框(我们称之为“记录”),如下所示:
| id | name |
|---|---|
| a1 | john |
| b"2 | alice |
| c3' | joe |
如果您注意到,主键列 (id) 值中可能包含单引号/双引号(如数据框中的第二行和第三行)。
我编写了以下 scala 代码来检查主键列值中的引号:
def checkForQuotesInPrimaryKeyColumn(primaryKey: String, records: DataFrame): Boolean = {
// Extract primary key column values
val pkcValues = records.select(primaryKey).collect().map(_(0)).toList
// Check for single and double quotes in the values
var checkForQuotes = false // indicates no quotes
breakable {
pkcValues.foreach(pkcValue => {
if (pkcValue.toString.contains("\"") || pkcValue.toString.contains("\'")) {
checkForQuotes = true
println("Value that has quotes: " + pkcValue.toString)
break()
}
})}
checkForQuotes
}
此代码有效。但它没有利用火花功能。我希望使用能够更快完成此任务的 spark 执行器(和其他功能)。
更新后的函数如下所示:
def checkForQuotesInPrimaryKeyColumnsUpdated(primaryKey: String, records: DataFrame): Boolean = {
val findQuotes = udf((s: String) => if (s.contains("\"") || s.contains("\'")) true else false)
records
.select(findQuotes(col(primaryKey)) as "quotes")
.filter(col("quotes") === true)
.collect()
.nonEmpty
}
当在具有 100 个条目的数据帧上运行时,单元测试在我的机器上为这两个函数提供了相似的运行时间。
更新后的功能是否比原始功能更快(和/或更好)?有什么方法可以改进功能吗?
【问题讨论】:
标签: scala apache-spark apache-spark-sql