Чтение первой таблицы и выполнение входных данных в искре SQL и вставка в другую таблицу - PullRequest
0 голосов
/ 06 мая 2020

Пожалуйста, предложите наилучший возможный код для требований ниже, мы используем Apache фреймворк Spark.

У меня есть таблица 1 и таблица 2, как показано ниже. Во-первых, нам нужно прочитать таблицу 1 на основе Test_id, затем выполнить соответствующие запросы (оба _SR C и _Target) один за другим, а затем вставить выходные данные в таблицу 2, а также выполнить базовое сравнение c (например, <, >, =, et c) с подсчетом выходных данных из запроса таблицы 1 и записью результатов в таблицу 2 с указанием даты и данных пользователя.

Заранее спасибо!

Таблица 1

enter image description here

Таблица 2 enter image description here

1 Ответ

2 голосов
/ 06 мая 2020

Пожалуйста, проверьте код ниже.

Создание таблицы 1:

scala> :paste
// Entering paste mode (ctrl-D to finish)

val df = Seq(
    (1,"select count(*) from dbnameaaa.tbl_name","select count(*) from dbnameaaa.tbl_name"),
    (2,"select count(*) from dbnameaaa.tmp_tbl","select count(*) from dbnameaaa.tmp_tbl"))
    .toDF("test_id","execution_script_src","execution_script_target")

// Exiting paste mode, now interpreting.

df: org.apache.spark.sql.DataFrame = [test_id: int, execution_script_src: string ... 1 more field]

scala> df.show(false)
+-------+---------------------------------------+---------------------------------------+
|test_id|execution_script_src                   |execution_script_target                |
+-------+---------------------------------------+---------------------------------------+
|1      |select count(*) from dbnameaaa.tbl_name|select count(*) from dbnameaaa.tbl_name|
|2      |select count(*) from dbnameaaa.tmp_tbl |select count(*) from dbnameaaa.tmp_tbl |
+-------+---------------------------------------+---------------------------------------+

Создание UDF для выполнения запроса и условий

scala> :paste
// Entering paste mode (ctrl-D to finish)

val execute = udf((query: String) => {
    try { spark.sql(query).map(_.getAs[Long](0)).collect.head }catch { case _: Exception => 0L }
})

val condition = udf((actual:Long,expected:Long) => {
   s"""{"=":"${if (actual == expected) "Pass" else "Fail"}","<":"${if (actual < expected) "Pass" else "Fail"}",">":"${if (actual > expected) "Pass" else "Fail"}","<>":"${if (actual != expected) "Pass" else "Fail"}"}"""
})

// Exiting paste mode, now interpreting.

execute: org.apache.spark.sql.expressions.UserDefinedFunction = UserDefinedFunction(<function1>,LongType,Some(List(StringType)))
condition: org.apache.spark.sql.expressions.UserDefinedFunction = UserDefinedFunction(<function2>,StringType,Some(List(LongType, LongType)))


Результат финальной таблицы

scala> :paste
// Entering paste mode (ctrl-D to finish)

df
.withColumn("actual_result",execute($"execution_script_src"))
.withColumn("expected_result",execute($"execution_script_target"))
.withColumn("test_condition",lit("[ =, <, >, <> ]"))
.withColumn("test_result",condition($"actual_result",$"expected_result"))
.withColumn("create_date",current_date)
.withColumn("modify_date",current_date)
.withColumn("created_by",lit(spark.sparkContext.sparkUser))
.withColumn("modified_by",lit(spark.sparkContext.sparkUser))
.withColumn("execute_date",current_date)
.show(false)

// Exiting paste mode, now interpreting.

+-------+---------------------------------------+---------------------------------------+-------------+---------------+---------------+----------------------------------------------+-----------+-----------+----------+-----------+------------+
|test_id|execution_script_src                   |execution_script_target                |actual_result|expected_result|test_condition |test_result                                   |create_date|modify_date|created_by|modified_by|execute_date|
+-------+---------------------------------------+---------------------------------------+-------------+---------------+---------------+----------------------------------------------+-----------+-----------+----------+-----------+------------+
|1      |select count(*) from dbnameaaa.tbl_name|select count(*) from dbnameaaa.tbl_name|11           |11             |[ =, <, >, <> ]|{"=":"Pass","<":"Fail",">":"Fail","<>":"Fail"}|2020-05-06 |2020-05-06 |srinivas  |srinivas   |2020-05-06  |
|2      |select count(*) from dbnameaaa.tmp_tbl |select count(*) from dbnameaaa.tmp_tbl |11           |22             |[ =, <, >, <> ]|{"=":"Fail","<":"Pass",">":"Fail","<>":"Pass"}|2020-05-06 |2020-05-06 |srinivas  |srinivas   |2020-05-06  |
+-------+---------------------------------------+---------------------------------------+-------------+---------------+---------------+----------------------------------------------+-----------+-----------+----------+-----------+------------+

...