如何在 Spark RDD (Java) 中按索引获取元素 [英] How to get element by Index in Spark RDD (Java)

查看:49
本文介绍了如何在 Spark RDD (Java) 中按索引获取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 rdd.firstwfirst() 方法,它为我提供 RDD 中的第一个元素.

I know the method rdd.firstwfirst() which gives me the first element in an RDD.

还有一个方法 rdd.take(num) 它给了我第一个num"元素.

Also there is the method rdd.take(num) Which gives me the first "num" elements.

但是不是有可能通过索引获取元素吗?

But isn't there a possibility to get an element by index?

谢谢.e

推荐答案

这应该可以通过首先索引 RDD 来实现.转换 zipWithIndex 提供了稳定的索引,按其原始顺序对每个元素进行编号.

This should be possible by first indexing the RDD. The transformation zipWithIndex provides a stable indexing, numbering each element in its original order.

给定:rdd = (a,b,c)

val withIndex = rdd.zipWithIndex // ((a,0),(b,1),(c,2))

要通过索引查找元素,这种形式没有用.首先我们需要使用索引作为键:

To lookup an element by index, this form is not useful. First we need to use the index as key:

val indexKey = withIndex.map{case (k,v) => (v,k)}  //((0,a),(1,b),(2,c))

现在,可以使用 PairRDD 中的 lookup 操作来按键查找元素:

Now, it's possible to use the lookup action in PairRDD to find an element by key:

val b = indexKey.lookup(1) // Array(b)

如果您希望在同一个 RDD 上经常使用 lookup,我建议缓存 indexKey RDD 以提高性能.

If you're expecting to use lookup often on the same RDD, I'd recommend to cache the indexKey RDD to improve performance.

如何使用 JavaAPI 是留给读者的练习.

How to do this using the Java API is an exercise left for the reader.

这篇关于如何在 Spark RDD (Java) 中按索引获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆