Pyspark Dataframe返回数据作为列Names

rdlzhqv9  于 12个月前  发布在  Spark
关注(0)|答案(1)|浏览(96)

我试图通过使用JDBC URL连接从一个dev-01工作区到dev-02工作区查询一个表的数据。但是在这样做的时候,数据框中的值作为头名称出现。
x1c 0d1x的数据
我使用的代码如下

test_query = f"""SELECT
 customer_short_code,
channel_name
FROM (
SELECT
customer_short_code,
channel_name,
ROW_NUMBER() OVER (PARTITION BY cast(customer_short_code as string) ORDER BY 
cast(channel_name as string) ) AS row_num
FROM
table_name where sales_subregion_name NOT LIKE 'Cerv. %' -- Replace with the actual 
table name
) AS RankedChannels
WHERE row_num = 1
"""
df_poc_sales = read_from_sandbox(jdbcUrl=dev_jdbc_url,query=test_query)
display(df_poc_sales)

字符串
从沙盒读取函数如下所示

def read_from_sandbox(jdbcUrl: str, query: str):
"""
Method is used to read data from sandbox instance

Args :
  jdbcUrl : jdbcurl of sandbox instance
  query : query is used to read dat
Return:
   spark dataframe
"""

df = (
    spark.read.format("jdbc")
    .option("url", jdbcUrl)
    .option("query", query)
    .option("driver", "com.databricks.client.jdbc.Driver")
    .load()
)
return df


经过分析发现,这个问题是由于行号或任何窗口函数。当我注解窗口函数的代码时,代码运行得很好。
有没有人遇到过类似的问题。
谢谢

k75qkfdt

k75qkfdt1#

根据Query SQL Server with Azure Databricks,连接到Azure SQL表的驱动程序是

driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"

字符串
我在PySpark中尝试过:在下面的代码中,我定义了窗口规范。在PySpark中应用转换。

window_spec = Window().partitionBy("customer_short_code").orderBy("channel_name")
def read_from_sandbox(jdbc_url: str, query: str):
    df = (
        spark.read.format("jdbc")
        .option("url", jdbc_url)
        .option("query", query)
        .option("driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver")
        .option("user", user)
        .option("password", password)
        .load()
    )
    return df
table02 = read_from_sandbox(jdbc_url, "SELECT * FROM table02 WHERE sales_subregion_name NOT LIKE 'Cerv. %'")
result_df = (
    table02
    .withColumn("row_num", F.row_number().over(window_spec))
    .filter(F.col("row_num") == 1)
    .select("customer_short_code", "channel_name")
)
result_df.show()

结果:

+-------------------+------------+
|customer_short_code|channel_name|
+-------------------+------------+
|          customer1|    channelA|
|          customer2|    channelC|
+-------------------+------------+

相关问题