2015-08-10 32 views
6

Sto iniziando con PySpark e sto avendo problemi con la creazione di DataFrames con oggetti nidificati.Spark - Creating Nested DataFrame

Questo è il mio esempio.

Ho utenti.

$ cat user.json 
{"id":1,"name":"UserA"} 
{"id":2,"name":"UserB"} 

Gli utenti hanno ordini.

$ cat order.json 
{"id":1,"price":202.30,"userid":1} 
{"id":2,"price":343.99,"userid":1} 
{"id":3,"price":399.99,"userid":2} 

E mi piace unirmi per ottenere una struttura in cui gli ordini sono nidificati negli utenti.

$ 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}]} 

Come posso farlo? C'è qualche tipo di join annidato o qualcosa di simile?

>>> 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) 

EDIT: So che c'è la possibilità di farlo usando unirsi e foldByKey, ma c'è un modo più semplice?

EDIT2: Sto utilizzando soluzione @ 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") 

aggiungo seconda struttura annidata

>>> 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) 

Dopo questa colonna nomi 'linee' dalle linee si perdono. Qualche idea?

MODIFICA 3: Ho provato a specificare lo schema manualmente.

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) 

Errore:

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'> 

risposta

6

Funzionerà solo in Spark 2.0 o poi

Prima abbiamo bisogno di un paio di importazioni:

from pyspark.sql.functions import struct, collect_list 

Il resto è una semplice aggregazione e unirsi:

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"]) 

Per i dati di esempio il risultato è:

combined.show(2, False) 
+---+-----+---------------------------+ 
|id |name |orders      | 
+---+-----+---------------------------+ 
|1 |UserA|[[1,202.3,1], [2,343.99,1]]| 
|2 |UserB|[[3,399.99,2]]    | 
+---+-----+---------------------------+ 

con schema:

combined.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) 

e JSON rappresentazione:

for x in combined.toJSON().collect(): 
    print(x)  
{"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}]} 
Non
-1

In primo luogo, è necessario utilizzare il userid come la chiave di join per la seconda DataFrame:

user.join(order, user.id == order.userid) 

quindi è possibile utilizzare un passo map per trasformare il record risultanti nel formato desiderato.

+0

davvero. 'Map' non è abbastanza. Se mi unisco agli utenti e agli ordini avrò 3 record. (e io voglio solo 2). Quindi ho anche bisogno di un qualche tipo di aggregazione (foldByKey per esempio) –

Problemi correlati