如何在Spark中实现尺寸缓慢变化(SCD2)类型2 [英] How to implement Slowly Changing Dimensions (SCD2) Type 2 in Spark

查看:94
本文介绍了如何在Spark中实现尺寸缓慢变化(SCD2)类型2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们想使用SQL Join在Spark中实现SCD2.我从Github那里获得了参考

We want to implement SCD2 in Spark using SQL Join. i got reference from Github

https://gist.github.com/rampage644/cc4659edd11d9a288c1b

但不是很清楚.

任何人都可以提供任何示例或参考来在Spark中实现SCD2

Can anybody provide any example or reference to implement SCD2 in spark

关于, 曼尼什(Manish)

Regards, Manish

推荐答案

在更新的Spark SQL方面有些过时,但这是一个示例 我使用Spark SQL试用了la Ralph Kimball,该方法行之有效,因此 可靠的.您可以运行它并且可以运行-但是文件逻辑和此类需求 要添加的内容-这是基于1.6的ETL SCD2逻辑的主体 语法,但可以在2.x中运行-并不难,但是您需要进行跟踪 通过并生成测试数据并跟踪每个步骤:

A little outdated in terms of newer Spark SQL, but here is an example I trialed a la Ralph Kimball using Spark SQL, that worked and is thus reliable. You can run it and it works - but file logic and such needs to be added - this is the body of the ETL SCD2 logic based on 1.6 syntax but run in 2.x - it is not that hard but you will need to trace through and generate test data and trace through each step:

   Some pre-processing required before script initiates, save a copy of existing and copy existing to the DIM_CUSTOMER_EXISTING.
   Write new output to DIM_CUSTOMER_NEW and then copy this to target, DIM_CUSTOMER_1 or DIM_CUSTOMER_2.
   The feed can also be re-created or LOAD OVERWRITE.
   ^^^ NEED SOME BETTER SCRIPTING AROUND THIS. ^^^ The Type 2 dimension is simply only Type 2 values, not a mixed Type 1 & Type 2.
   DUMPs that are accumulative can be in fact pre-processed to get the delta.
   Use case assumes we can have N input for a person with a date validity / extract supplied.
   SPARK 1.6 SQL based originally, not updated yet to SPARK 2.x SQL with nested correlated subquery support.
   CUST_CODE cannot changes unless a stable Primary Key.
   This approach handles no input, delta input, same input, all input, and can catch up and need not be run-date based.
   ^^^ Works best with deltas, as if pass all data and there is no change then still have make a dummy entry with all the same values else it will have gaps in key range 
   which means will not be able to link facts to dimensions in all cases. I.e. the discard logic works only in terms of a pure delta feed. All data can be passed but only 
   the current delta. Problem becomes difficult to solve in that we must then look for changes over different rows and expand date range, a little too complicated imho. 
   The dummy entries in the dimensions are not a huge issue. The problem is a little more difficult in such a less mutable environment, in KUDU it easier to solve. 
   Ideally there would be some sort of preprocessor that checks which fields have changed and only then passed on, but that may be a bridge too far.
   HENCE IT IS A COMPROMISE ALGORITHM necessarily. ^^^
   No Deletions processed.
   Multi-step processing for SQL required in some cases. Gaps in key ranges difficult to avoid with set processing.
   No out of order processing, that would mean re-processing all. Works on a whole date/day basis, if run more than once per day in batch then would need timestamp instead.

   0.1 Any difference analysis on existimg dumps only possible if the dumps are accumulative. If they are transactional deltas only, then this is not required.
       Care to be taken here.
   0.2 If we want only the last update for a given date, then do that here by method of Partitioning and Ranking and filtering out.
       These are all pre-processing steps as are the getting of the dimension data from which table.

   0.3 Issue is that of small files, but that is not an issue here at xxx. RAW usage only as written to KUDU in a final step.

实际编码:

Actual coding:

import org.apache.spark.sql.SparkSession
val sparkSession = SparkSession
   .builder
   .master("local") // Not a good idea
   .appName("Type 2 dimension update")
   .config("spark.sql.crossJoin.enabled", "true") // Needed to add this
   .getOrCreate()

spark.sql("drop table if exists DIM_CUSTOMER_EXISTING")
spark.sql("drop table if exists DIM_CUSTOMER_NEW")
spark.sql("drop table if exists FEED_CUSTOMER")
spark.sql("drop table if exists DIM_CUSTOMER_TEMP")
spark.sql("drop table if exists DIM_CUSTOMER_WORK")
spark.sql("drop table if exists DIM_CUSTOMER_WORK_2")
spark.sql("drop table if exists DIM_CUSTOMER_WORK_3")
spark.sql("drop table if exists DIM_CUSTOMER_WORK_4")

spark.sql("create table DIM_CUSTOMER_EXISTING (DWH_KEY int, CUST_CODE String, CUST_NAME String, ADDRESS_CITY String, SALARY int, VALID_FROM_DT String, VALID_TO_DT String) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' STORED AS TEXTFILE LOCATION  '/FileStore/tables/alhwkf661500326287094' ")

spark.sql("create table DIM_CUSTOMER_NEW (DWH_KEY int, CUST_CODE String, CUST_NAME String, ADDRESS_CITY String, SALARY int, VALID_FROM_DT String, VALID_TO_DT String) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' STORED AS TEXTFILE LOCATION  '/FileStore/tables/DIM_CUSTOMER_NEW_3' ")

spark.sql("CREATE TABLE FEED_CUSTOMER (CUST_CODE String, CUST_NAME String, ADDRESS_CITY String, SALARY int, VALID_DT String) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' STORED AS TEXTFILE LOCATION  '/FileStore/tables/mhiscfsv1500226290781' ")

// 1. Get maximum value in dimension, this differs to other RDD approach, issues in parallel? May be other way to be done! Check, get a DF here and this is the interchangability
val max_val = spark.sql("select max(dwh_key) from DIM_CUSTOMER_EXISTING")

//max_val.show()
val null_count = max_val.filter("max(DWH_KEY) is null").count()
var max_Dim_Key = 0;
if ( null_count == 1 ) {
     max_Dim_Key = 0
} else {
     max_Dim_Key = max_val.head().getInt(0)
}

//2. Cannot do simple difference processing. The values of certain fields could be flip-flopping over time. A too simple MINUS will not work well. Need to process relative to
//   youngest existing record etc. and roll the transactions forward. Hence we will not do any sort of difference analysis between new dimension data and existing dimension
//   data in any way.
//   DO NOTHING.

//3. Capture new stuff to be inserted. 
//   Some records for a given business key can be linea recta inserted as there have been no mutations to consider at all as there is nothing in current Staging. Does not mean
//   delete.
//   Also, the older mutations need not be re-processed, only the youngest! The younger one may need closing off or not, need to decide if it is now 
//   copied across or subject to updating in this cycle, depends on the requirements.
//  Older mutations copied across immediately.
//  DELTA not always strictly speaking needed, but common definitions. Some ranking required.

spark.sql("""insert into  DIM_CUSTOMER_NEW     select * 
                                                 from DIM_CUSTOMER_EXISTING 
                                                where CUST_CODE not in (select distinct CUST_CODE FROM FEED_CUSTOMER) """) // This does not need RANKing, DWH Key retained.

spark.sql("""create table DIM_CUSTOMER_TEMP as select *, dense_rank() over (partition by CUST_CODE order by VALID_FROM_DT desc) as RANK 
                                             from DIM_CUSTOMER_EXISTING """)

spark.sql("""insert into DIM_CUSTOMER_NEW  select DWH_KEY, CUST_CODE, CUST_NAME, ADDRESS_CITY, SALARY, VALID_FROM_DT, VALID_TO_DT 
                                          from DIM_CUSTOMER_TEMP 
                                         where CUST_CODE in (select distinct CUST_CODE from FEED_CUSTOMER)
                                           and RANK <> 1 """) 
// For updating of youngest record in terms of SLCD, we use use AND RANK <> 1 to filter these out here as we want to close off the period in this record, but other younger 
// records can be passed through immediately with their retained DWH Key.

//4. Combine Staging and those existing facts required. The result of this eventually will be stored in DIM_CUSTOMER_NEW which can be used for updating a final target. 
//   Issue here is that DWH Key not yet set and different columns. DWH key can be set last.
//4.1 Get records to process, the will have the status NEW.

spark.sql("""create table DIM_CUSTOMER_WORK (DWH_KEY int, CUST_CODE String, CUST_NAME String, ADDRESS_CITY String, SALARY int, VALID_FROM_DT String, VALID_TO_DT String, RECSTAT String)  """)
spark.sql("""insert  into DIM_CUSTOMER_WORK    select  0, CUST_CODE, CUST_NAME, ADDRESS_CITY, SALARY, VALID_DT, '2099-12-31', "NEW"
                                             from  FEED_CUSTOMER """)
//4.2 Get youngest already existing dimension record to process in conjunction with newer values.
spark.sql("""insert  into DIM_CUSTOMER_WORK    select  DWH_KEY, CUST_CODE, CUST_NAME, ADDRESS_CITY, SALARY, VALID_FROM_DT, VALID_TO_DT, "OLD"
                                             from  DIM_CUSTOMER_TEMP 
                                            where  CUST_CODE in (select distinct CUST_CODE from FEED_CUSTOMER)
                                              and RANK = 1 """) 

// 5. ISSUE with first record in a set. It is not a delta or is used for making a delta, need to know what to do or bypass, depends on case.
//    Here we are doing deltas, so first rec is a complete delta
//    RECSTAT to be filtered out at end
//    NEW, 1 = INSERT  --> checked, is correct way, can do in others. No delta computation required
//    OLD, 1 = DO NOTHING
//    else do delta and INSERT

//5.1 RANK and JOIN to get before and after images in CDC format so that we can decide what needs to be closed off.
//    Get the new DWH key values + offset, there may exist gaps eventually.

spark.sql(""" create table DIM_CUSTOMER_WORK_2  as select *, rank() over (partition by CUST_CODE order by VALID_FROM_DT asc) as rank FROM DIM_CUSTOMER_WORK  """)

//DWH_KEY, CUST_CODE, CUST_NAME, BIRTH_CITY, SALARY,VALID_FROM_DT, VALID_TO_DT, "OLD"

spark.sql(""" create table DIM_CUSTOMER_WORK_3 as 
                                     select  T1.DWH_KEY as T1_DWH_KEY, T1.CUST_CODE as T1_CUST_CODE, T1.rank as CURR_RANK, T2.rank as NEXT_RANK, 
                                             T1.VALID_FROM_DT as CURR_VALID_FROM_DT, T2.VALID_FROM_DT as NEXT_VALID_FROM_DT, 
                                             T1.VALID_TO_DT as CURR_VALID_TO_DT, T2.VALID_TO_DT as NEXT_VALID_TO_DT, 
                                             T1.CUST_NAME as CURR_CUST_NAME, T2.CUST_NAME as NEXT_CUST_NAME,
                                             T1.SALARY as CURR_SALARY, T2.SALARY as NEXT_SALARY, 
                                             T1.ADDRESS_CITY as CURR_ADDRESS_CITY, T2.ADDRESS_CITY as NEXT_ADDRESS_CITY, 
                                             T1.RECSTAT as CURR_RECSTAT, T2.RECSTAT as NEXT_RECSTAT   
                                       from DIM_CUSTOMER_WORK_2 T1 LEFT OUTER JOIN DIM_CUSTOMER_WORK_2 T2 
                                         on T1.CUST_CODE = T2.CUST_CODE AND T2.rank = T1.rank + 1  """)  

//5.2 Get the data for computing new Dimension Surrogate DWH Keys, must execute new query or could use DF's and RDS, RDDs, but chosen for SPARK SQL as aeasier to follow
spark.sql(s""" create table DIM_CUSTOMER_WORK_4 as 
                                     select  *, row_number() OVER( ORDER BY T1_CUST_CODE) as ROW_NUMBER, '$max_Dim_Key' as DIM_OFFSET 
                                       from DIM_CUSTOMER_WORK_3   """)  

 //spark.sql("""SELECT * FROM DIM_CUSTOMER_WORK_4     """).show()
 //Execute the above to see results, could not format here.


//5.3 Process accordingly and check if no change at all, if no change can get holes in the sequence numbers, that is not an issue. NB: NOT DOING THIS DUE TO COMPLICATIONS !!! 
//    See sample data above for decision-making on what to do. NOTE THE FACT THAT WE WOULD NEED A PRE_PROCCESOR TO CHECK IF FIELD OF INTEREST ACTUALLY CHANGED
//    to get the best result. 
//    We could elaborate and record via an extra step if there were only two records per business key and if all the current and only next record fields were all the same, 
//    we could disregard the first and the second record. Will attempt that later as an extra optimization. As soon as there are more than two here, then this scheme packs up 
//    Some effort still needed.

//5.3.1 Records that just need to be closed off. The previous version gets an appropriate DATE - 1. Dates must not overlap.  
//      No check on whether data changed or not due to issues above.

spark.sql("""insert into  DIM_CUSTOMER_NEW  select T1_DWH_KEY, T1_CUST_CODE, CURR_CUST_NAME, CURR_ADDRESS_CITY, CURR_SALARY, 
                                               CURR_VALID_FROM_DT, cast(date_sub(cast(NEXT_VALID_FROM_DT as DATE), 1) as STRING)
                                          from DIM_CUSTOMER_WORK_4 
                                         where CURR_RECSTAT = 'OLD'  """)  

//5.3.2 Records that are the last in the sequence must have high end 2099-12-31 set, which has already been done. 
//      No check on whether data changed or not due to issues above.
spark.sql("""insert into  DIM_CUSTOMER_NEW  select ROW_NUMBER + DIM_OFFSET, T1_CUST_CODE, CURR_CUST_NAME, CURR_ADDRESS_CITY, CURR_SALARY, 
                                               CURR_VALID_FROM_DT, CURR_VALID_TO_DT
                                          from DIM_CUSTOMER_WORK_4 
                                         where NEXT_RANK is null  """)  

//5.3.3 
spark.sql("""insert into  DIM_CUSTOMER_NEW  select ROW_NUMBER + DIM_OFFSET, T1_CUST_CODE, CURR_CUST_NAME, CURR_ADDRESS_CITY, CURR_SALARY, 
                                               CURR_VALID_FROM_DT, cast(date_sub(cast(NEXT_VALID_FROM_DT as DATE), 1) as STRING)
                                          from DIM_CUSTOMER_WORK_4 
                                         where CURR_RECSTAT = 'NEW' 
                                           and NEXT_RANK is not null""")  
spark.sql("""SELECT * FROM DIM_CUSTOMER_NEW   """).show()

// So, the question is if we could have done without JOINing and just sorted due to gap processing. This was derived off the delta processing but it turned out a little 
// different.
// Well we did need the JOIN for next date at least, so if we add some optimization it still holds.
// My logic applied here per different steps, may well be less steps, left as is.

//6. The copy / insert to get a new big target table version and re-compile views. Outside of this actual processing. Logic performed elsewhere.

// NOTE now that 2.x supports nested correlated sub-queries are supported, so would need to re-visit this at a later point, but can leave as is.
// KUDU means no more restating.

对数据进行采样,以便您了解为示例生成的数据:

Sample data so you know what to generate for the examples:

+-------+---------+----------------+------------+------+-------------+-----------+
|DWH_KEY|CUST_CODE|       CUST_NAME|ADDRESS_CITY|SALARY|VALID_FROM_DT|VALID_TO_DT|
+-------+---------+----------------+------------+------+-------------+-----------+
|    230|  E222222|   Pete Saunders|       Leeds| 75000|   2013-03-09| 2099-12-31|
|    400|  A048901|  John Alexander|     Calgary| 22000|   2015-03-24| 2017-10-22|
|    402|  A048901|  John Alexander|  Wellington| 47000|   2017-10-23| 2099-12-31|
|    403|  B787555|     Mark de Wit|Johannesburg| 49500|   2017-10-02| 2099-12-31|
|    406|  C999666|      Daya Dumar|      Mumbai| 50000|   2016-12-16| 2099-12-31|
|    404|  C999666|      Daya Dumar|      Mumbai| 49000|   2016-11-11| 2016-12-14|
|    405|  C999666|      Daya Dumar|      Mumbai| 50000|   2016-12-15| 2016-12-15|
|    300|  A048901|  John Alexander|     Calgary| 15000|   2014-03-24| 2015-03-23|
+-------+---------+----------------+------------+------+-------------+-----------+

这篇关于如何在Spark中实现尺寸缓慢变化(SCD2)类型2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆