簡體   English   中英

Pyspark:轉換類型為字符串的多重連接條件

[英]Pyspark : Multiple join condition with cast type as string

在 Spark SQL 中,我需要將 as_of_date 轉換為字符串,並在連接后對 3 個表和 select 表 1、2 和 3 中的所有行和列進行多重內連接。 示例表架構如下所示

Tablename : Table_01 alias t1

Column      | Datatype
as_of_date  | String
Tablename   | String
Credit_Card | String


Tablename : Table_02   alias t2

Column        | Datatype
as_of_date    | INT
Customer_name | String
tablename     | string

Tablename : Table_03   alias t3

Column        | Datatype
as_of_date    | String
tablename     | String 
address       | String

加入用例:

t1.as_of_date = t2.as_of_date AND t1.tablename = t2.tablename
t2.as_of_date = t3.as_of_date AND t2.tablename = t3.tablename      

   

表已經在 hive 中創建,我正在對這些表進行 spark 轉換,並將 table_02 中的 as_of_date 轉換為字符串。

我想到了兩種方法,但我不確定哪種方法最好

方法一:

df = spark.sql("select t1.*,t2.*,t3.* from table_1 t1 where cast(t1.as_of_date as string) inner join table_t2 t2 on t1.as_of_date = t2.as_of_date AND t1.tablename = t2.tablename inner join table_03 t3 on t2.as_of_date = t3.as_of_date and t2.tablename = t3.tablename")

方法二:

df_t1 = spark.sql("select * from table_01");
df_t2 = spark.sql("select * from table_02");
df_t3 = spark.sql("select * from table_03");

## Cast as_of_date as String if dtype as of date is int 
if dict(df_t2.dtypes)["as_of_date"] == 'int':
        df_t1["as_of_date"].cast(cast(StringType())
                                  
## Join Condition 
df = df_t1.alias('t1').join(df_t2.alias('t2'),on="t1.tablename=t2.tablename AND t1.as_of_date = t2.as_of_date", how='inner').join(df_t3.alias('t3'),on="t2.as_of_date = t3.as_of_date AND t2.tablename = t3.tablename",how='inner').select('t1.*,t2.*,t3.*')

我覺得使用方法 2 是冗長的,我需要一些關於我應該使用 go 的方法的建議,以便於維護和使用的腳本

我建議如下直接使用 Spark SQL。 無論數據類型如何,您都可以將所有表中的每個 as_of_date 列轉換為字符串。 您想將 integer 轉換為字符串,但是如果您也將字符串轉換為字符串,則沒有害處。

df = spark.sql("""
    select t1.*, t2.*, t3.*
    from t1
    join t2 on string(t1.as_of_date) = string(t2.as_of_date) AND t1.tablename = t2.tablename
    join t3 on string(t2.as_of_date) = string(t3.as_of_date) AND t2.tablename = t3.tablename
""")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM