简体   繁体   English

如何获取scala Apache rdd [row]中前一行的值?

[英]How to get value of previous row in scala apache rdd[row]?

I need to get value from previous or next row while Im iterating through RDD[Row] 我需要遍历RDD [Row]时从上一行或下一行获取价值

(10,1,string1)
(11,1,string2)
(21,1,string3)
(22,1,string4)

I need to sum strings for rows where difference between 1st value is not higher than 3. 2nd value is ID. 我需要对第一个值之间的差不大于3的行的字符串求和。第二个值是ID。 So the result should be: 因此结果应为:

(1, string1string2)
(1, string3string4)

I tried use groupBy, reduce, partitioning but still I can't achieve what I want. 我尝试使用groupBy,reduce,进行分区,但仍然无法实现所需的功能。

I'm trying to make something like this(I know it's not proper way): 我正在尝试做这样的事情(我知道这是不正确的方式):

rows.groupBy(row => {
      row(1)
    }).map(rowList => {
      rowList.reduce((acc, next) => {
        diff = next(0) - acc(0)
        if(diff <= 3){
          val strings = acc(2) + next(2)
          (acc(1), strings)
        }else{
          //create new group to aggregatre strings
          (acc(1), acc(2))
        }
      })
    })

I wonder if my idea is proper to solve this problem. 我想知道我的想法是否适合解决这个问题。 Looking for help! 寻求帮助!

I think you can use sqlContext to Solve your problem by using lag function 我认为您可以使用sqlContext通过使用lag函数解决问题

Create RDD: 创建RDD:

val rdd = sc.parallelize(List(
(10, 1, "string1"),
(11, 1, "string2"),
(21, 1, "string3"),
(22, 1, "string4"))
)

Create DataFrame: 创建数据框:

val df = rdd.map(rec => (rec._1.toInt, rec._2.toInt, rec._3.toInt)).toDF("a", "b", "c")

Register your Dataframe: 注册您的数据框:

df.registerTempTable("df")

Query the result: 查询结果:

val res = sqlContext.sql("""
SELECT CASE WHEN l < 3 THEN ROW_NUMBER() OVER (ORDER BY b) - 1
ELSE ROW_NUMBER() OVER (ORDER BY b)
END m, b, c 
FROM (
SELECT b,
(a - CASE WHEN lag(a, 1) OVER (ORDER BY a) is not null
THEN lag(a, 1) OVER (ORDER BY a)
ELSE 0
END) l, c
FROM df) A 
""")

Show the Results: 显示结果:

res.show

I Hope this will Help. 我希望这将有所帮助。

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

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