Mac*_*ski 13 python dataframe apache-spark apache-spark-sql pyspark
我从PySpark开始,我在使用嵌套对象创建DataFrame时遇到了麻烦.
这是我的榜样.
我有用户.
$ cat user.json
{"id":1,"name":"UserA"}
{"id":2,"name":"UserB"}
Run Code Online (Sandbox Code Playgroud)
用户有订单.
$ cat order.json
{"id":1,"price":202.30,"userid":1}
{"id":2,"price":343.99,"userid":1}
{"id":3,"price":399.99,"userid":2}
Run Code Online (Sandbox Code Playgroud)
我喜欢加入它来获得这样一个结构,其中订单是嵌套在用户中的数组.
$ cat join.json
{"id":1, "name":"UserA", "orders":[{"id":1,"price":202.30,"userid":1},{"id":2,"price":343.99,"userid":1}]}
{"id":2,"name":"UserB","orders":[{"id":3,"price":399.99,"userid":2}]}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点 ?是否有任何类型的嵌套连接或类似的东西?
>>> user = sqlContext.read.json("user.json")
>>> user.printSchema();
root
|-- id: long (nullable = true)
|-- name: string (nullable = true)
>>> order = sqlContext.read.json("order.json")
>>> order.printSchema();
root
|-- id: long (nullable = true)
|-- price: double (nullable = true)
|-- userid: long (nullable = true)
>>> joined = sqlContext.read.json("join.json")
>>> joined.printSchema();
root
|-- id: long (nullable = true)
|-- name: string (nullable = true)
|-- orders: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- id: long (nullable = true)
| | |-- price: double (nullable = true)
| | |-- userid: long (nullable = true)
Run Code Online (Sandbox Code Playgroud)
编辑:我知道有可能使用join和foldByKey这样做,但有没有更简单的方法?
EDIT2:我正在使用@ zero323的解决方案
def joinTable(tableLeft, tableRight, columnLeft, columnRight, columnNested, joinType = "left_outer"):
tmpTable = sqlCtx.createDataFrame(tableRight.rdd.groupBy(lambda r: r.asDict()[columnRight]))
tmpTable = tmpTable.select(tmpTable._1.alias("joinColumn"), tmpTable._2.data.alias(columnNested))
return tableLeft.join(tmpTable, tableLeft[columnLeft] == tmpTable["joinColumn"], joinType).drop("joinColumn")
Run Code Online (Sandbox Code Playgroud)
我添加第二个嵌套结构'行'
>>> lines = sqlContext.read.json(path + "lines.json")
>>> lines.printSchema();
root
|-- id: long (nullable = true)
|-- orderid: long (nullable = true)
|-- product: string (nullable = true)
orders = joinTable(order, lines, "id", "orderid", "lines")
joined = joinTable(user, orders, "id", "userid", "orders")
joined.printSchema()
root
|-- id: long (nullable = true)
|-- name: string (nullable = true)
|-- orders: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- id: long (nullable = true)
| | |-- price: double (nullable = true)
| | |-- userid: long (nullable = true)
| | |-- lines: array (nullable = true)
| | | |-- element: struct (containsNull = true)
| | | | |-- _1: long (nullable = true)
| | | | |-- _2: long (nullable = true)
| | | | |-- _3: string (nullable = true)
Run Code Online (Sandbox Code Playgroud)
在此列之后,行中的名称将丢失.有任何想法吗 ?
编辑3:我试图手动指定架构.
from pyspark.sql.types import *
fields = []
fields.append(StructField("_1", LongType(), True))
inner = ArrayType(lines.schema)
fields.append(StructField("_2", inner))
new_schema = StructType(fields)
print new_schema
grouped = lines.rdd.groupBy(lambda r: r.orderid)
grouped = grouped.map(lambda x: (x[0], list(x[1])))
g = sqlCtx.createDataFrame(grouped, new_schema)
Run Code Online (Sandbox Code Playgroud)
错误:
TypeError: StructType(List(StructField(id,LongType,true),StructField(orderid,LongType,true),StructField(product,StringType,true))) can not accept object in type <class 'pyspark.sql.types.Row'>
Run Code Online (Sandbox Code Playgroud)
use*_*411 20
这仅适用于Spark 2.0或更高版本
首先,我们需要一些进口:
from pyspark.sql.functions import struct, collect_list
Run Code Online (Sandbox Code Playgroud)
其余的是一个简单的聚合和连接:
orders = spark.read.json("/path/to/order.json")
users = spark.read.json("/path/to/user.json")
combined = users.join(
orders
.groupBy("userId")
.agg(collect_list(struct(*orders.columns)).alias("orders"))
.withColumnRenamed("userId", "id"), ["id"])
Run Code Online (Sandbox Code Playgroud)
对于示例数据,结果是:
combined.show(2, False)
Run Code Online (Sandbox Code Playgroud)
+---+-----+---------------------------+
|id |name |orders |
+---+-----+---------------------------+
|1 |UserA|[[1,202.3,1], [2,343.99,1]]|
|2 |UserB|[[3,399.99,2]] |
+---+-----+---------------------------+
Run Code Online (Sandbox Code Playgroud)
与架构:
combined.printSchema()
Run Code Online (Sandbox Code Playgroud)
root
|-- id: long (nullable = true)
|-- name: string (nullable = true)
|-- orders: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- id: long (nullable = true)
| | |-- price: double (nullable = true)
| | |-- userid: long (nullable = true)
Run Code Online (Sandbox Code Playgroud)
和JSON表示:
for x in combined.toJSON().collect():
print(x)
Run Code Online (Sandbox Code Playgroud)
{"id":1,"name":"UserA","orders":[{"id":1,"price":202.3,"userid":1},{"id":2,"price":343.99,"userid":1}]}
{"id":2,"name":"UserB","orders":[{"id":3,"price":399.99,"userid":2}]}
Run Code Online (Sandbox Code Playgroud)