将 SQL 模式分配给 Spark DataFrame [英] Assign SQL schema to Spark DataFrame

查看:32
本文介绍了将 SQL 模式分配给 Spark DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将我团队的旧 Redshift SQL 代码转换为 Spark SQL 代码.我见过的所有 Spark 示例都使用 StructTypeStructField 以非 SQL 方式定义架构,我更喜欢在 SQL 中定义架构,因为大多数我的用户知道 SQL 但不知道 Spark.

I'm converting my team's legacy Redshift SQL code to Spark SQL code. All the Spark examples I've seen define the schema in a non-SQL way using StructType and StructField and I'd prefer to define the schema in SQL, since most of my users know SQL but not Spark.

这是我现在正在做的丑陋的解决方法.有没有更优雅的方法,不需要定义一个空表就可以提取 SQL 模式?

This is the ugly workaround I'm doing now. Is there a more elegant way that doesn't require defining an empty table just so that I can pull the SQL schema?

create_table_sql = '''
CREATE TABLE public.example (
  id LONG,
  example VARCHAR(80)
)'''
spark.sql(create_table_sql)
schema = spark.sql("DESCRIBE public.example").collect()
s3_data = spark.read.\
option("delimiter", "|")\
.csv(
    path="s3a://"+s3_bucket_path,
    schema=schema
)\
.saveAsTable('public.example')

推荐答案

是的,有一种方法可以从字符串创建模式,尽管我不确定它是否真的像 SQL!所以你可以使用:

Yes there is a way to create schema from string although I am not sure if it really looks like SQL! So you can use:

from pyspark.sql.types import _parse_datatype_string

_parse_datatype_string("id: long, example: string")

这将创建下一个架构:

  StructType(List(StructField(id,LongType,true),StructField(example,StringType,true)))

或者您也可能有一个复杂的架构:

Or you may have a complex schema as well:

schema = _parse_datatype_string("customers array<struct<id: long, name: string, address: string>>")

StructType(
  List(StructField(
    customers,ArrayType(
      StructType(
        List(
          StructField(id,LongType,true),
          StructField(name,StringType,true),
          StructField(address,StringType,true)
        )
      ),true),true)
  )
)

您可以在此处查看更多示例

这篇关于将 SQL 模式分配给 Spark DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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