繁体   English   中英

Spark 1.6 scala创建数据行

[英]Spark 1.6 scala create data rows

我有以下代码。

val sqlContext = new org.apache.spark.sql.hive.HiveContext(sc)
val baseDF = sqlContext.read.json(fileFullPath)

我的json有两个感兴趣的领域:ProductId和Quantity。 我在找什么

{
    "sales": {
        "saledate": "17Mar2008",
        "sale": [{
            "productid": 1,
            "quantity": 10
        }, {
            "productid": 2,
            "quantity": 1
        }, {
            "productid": 3,
            "quantity": 3
        }, {
            "productid": 4,
            "quantity": 5
        }]
    }
}

我想将其更改为火花RDD或DF,它有2列,产量和数量,但基于数量的多行。 我想要每个数量1。

在上面的例子中,产品1有10行,产品2有1,产品3有3,产品4有5行,共19行,即#rows = sum(quantity)。

任何帮助赞赏。 我正在使用spark 1.6.2和scala。

这应该做的事情:

import org.apache.spark.sql.functions._

val sqlContext = new org.apache.spark.sql.hive.HiveContext(sc)
import sqlContext.implicits._

val baseDF = sqlContext.read.json(fileFullPath)
val listFromQuantity = udf { quantity: Int => List.fill(quantity)(quantity) }

baseDF.select(explode($"sales.sale")).select($"col.productId", explode(listFromQuantity($"col.quantity"))).show()

哪个回报:

+---------+--------+
|productId|quantity|
+---------+--------+
|        1|      10|
|        1|      10|
|        1|      10|
|        1|      10|
|        1|      10|
|        1|      10|
|        1|      10|
|        1|      10|
|        1|      10|
|        1|      10|
|        2|       1|
|        3|       3|
|        3|       3|
|        3|       3|
|        4|       5|
|        4|       5|
|        4|       5|
|        4|       5|
|        4|       5|
+---------+--------+

如果您希望第二列中有一个数量(例如,值为1而不是5 ),则应将List.fill(quantity)(quantity)替换为List.fill(quantity)(1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM