是否可以从PySpark数据框轻松创建Kudu表?

时间:2018-10-31 09:50:15

标签: python-3.x pyspark apache-kudu

理想地,以下代码片段可以正常工作:

import kudu 
from kudu.client import Partitioning

df = … #some spark dataframe 

# Connect to Kudu master server 
client = kudu.connect(host=‘…‘, port=7051)

# infer schema from spark dataframe
schema = df.schema 

# Define partitioning schema 
partitioning = Partitioning().add_hash_partitions(column_names=['key'], num_buckets=3) 

# Create new table 
client.create_table('dev.some_example', schema, partitioning)

但是client.create_table需要一个kudu.schema.Schema而不是数据帧中的结构。但是,在Scala中,您可以执行此操作(来自https://kudu.apache.org/docs/developing.html):

kuduContext.createTable(
"dev.some_example", df.schema, Seq("key"),
new CreateTableOptions()
    .setNumReplicas(1)
    .addHashPartitions(List("key").asJava, 3))

现在我想知道是否可以在不使用kudu模式生成器手动定义每个列的情况下使用PySpark进行相同的操作?

1 个答案:

答案 0 :(得分:0)

因此,我为自己编写了一个帮助程序函数,用于将PySpark Dataframe模式转换为kudu.schema.Schema,希望对您有所帮助。反馈表示赞赏!

旁注,您可能想添加或编辑数据类型映射。

import kudu
from kudu.client import Partitioning
def convert_to_kudu_schema(df_schema, primary_keys):
    builder = kudu.schema.SchemaBuilder()
    data_type_map = {
        "StringType":kudu.string,
        "LongType":kudu.int64,
        "IntegerType":kudu.int32,
        "FloatType":kudu.float,
        "DoubleType":kudu.double,
        "BooleanType":kudu.bool,
        "TimestampType":kudu.unixtime_micros,
    }

    for sf in df_schema:
        pk = False
        nullable=sf.nullable
        if (sf.name in primary_keys): 
            pk = True
            nullable = False

        builder.add_column(
            name=sf.name,
            nullable=nullable,
            type_=data_type_map[str(sf.dataType)]
        )
    builder.set_primary_keys(primary_keys)
    return builder.build()

您可以这样称呼它:

kudu_schema = convert_to_kudu_schema(df.schema,primary_keys=["key1","key2"])

我仍然愿意寻求更优雅的解决方案。 ;)