创建一个涉及ArrayType的Pyspark模式

bli*_*web 7 schema rdd pyspark spark-dataframe

我正在尝试为新的DataFrame创建架构,并尝试了方括号和关键字的各种组合,但是无法弄清楚如何使这项工作有效。我目前的尝试:

from pyspark.sql.types import *

schema = StructType([
  StructField("User", IntegerType()),
  ArrayType(StructType([
    StructField("user", StringType()),
    StructField("product", StringType()),
    StructField("rating", DoubleType())]))
  ])
Run Code Online (Sandbox Code Playgroud)

返回错误:

elementType should be DataType
Traceback (most recent call last):
 File "/usr/hdp/current/spark2-client/python/pyspark/sql/types.py", line 290, in __init__
assert isinstance(elementType, DataType), "elementType should be DataType"
AssertionError: elementType should be DataType   
Run Code Online (Sandbox Code Playgroud)

我已经用谷歌搜索过,但是到目前为止,还没有很好的对象数组实例。

小智 10

您将需要额外StructFieldArrayType财产。这应该工作:

from pyspark.sql.types import *

schema = StructType([
  StructField("User", IntegerType()),
  StructField("My_array", ArrayType(
      StructType([
          StructField("user", StringType()),
          StructField("product", StringType()),
          StructField("rating", DoubleType())
      ])
   )
])
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请检查此链接:http : //nadbordrozd.github.io/blog/2016/05/22/one-weird-trick-that-will-fix-your-pyspark-schemas/