Spark的RDD操作之Join大全
一、RDD的Join操作有哪些?
?
(一)Join:Join類似于SQL的inner join操作,返回結果是前面和后面集合中配對成功的,過濾掉關聯不上的。源代碼如下:
/**
* Return an RDD containing all pairs of elements with matching keys in `this` and `other`. Each
* pair of elements will be returned as a (k, (v1, v2)) tuple, where (k, v1) is in `this` and
* (k, v2) is in `other`. Uses the given Partitioner to partition the output RDD.
*/
def join[W](other: RDD[(K, W)], partitioner: Partitioner): RDD[(K, (V, W))] = self.withScope {
this.cogroup(other, partitioner).flatMapValues( pair =>
for (v <- pair._1.iterator; w <- pair._2.iterator) yield (v, w)
)
}
?
(二)leftOuterJoin:leftOuterJoin類似于SQL中的左外關聯left outer join,返回結果以前面的RDD為主,關聯不上的記錄為空。聲明如下:
?
/**
* Perform a left outer join of `this` and `other`. For each element (k, v) in `this`, the
* resulting RDD will either contain all pairs (k, (v, Some(w))) for w in `other`, or the
* pair (k, (v, None)) if no elements in `other` have key k. Uses the given Partitioner to
* partition the output RDD.
*/
def leftOuterJoin[W](
other: RDD[(K, W)],
partitioner: Partitioner): RDD[(K, (V, Option[W]))] = self.withScope {
this.cogroup(other, partitioner).flatMapValues { pair =>
if (pair._2.isEmpty) {
pair._1.iterator.map(v => (v, None))
} else {
for (v <- pair._1.iterator; w <- pair._2.iterator) yield (v, Some(w))
}
}
}
?
?(三)rightOuterJoin:rightOuterJoin類似于SQL中的有外關聯right outer join,返回結果以參數也就是右邊的RDD為主,關聯不上的記錄為空。聲明如下:
/**
* Perform a right outer join of `this` and `other`. For each element (k, w) in `other`, the
* resulting RDD will either contain all pairs (k, (Some(v), w)) for v in `this`, or the
* pair (k, (None, w)) if no elements in `this` have key k. Uses the given Partitioner to
* partition the output RDD.
*/
def rightOuterJoin[W](other: RDD[(K, W)], partitioner: Partitioner)
: RDD[(K, (Option[V], W))] = self.withScope {
this.cogroup(other, partitioner).flatMapValues { pair =>
if (pair._1.isEmpty) {
pair._2.iterator.map(w => (None, w))
} else {
for (v <- pair._1.iterator; w <- pair._2.iterator) yield (Some(v), w)
}
}
}
?
二、實戰操作
?
下面我們用一個非常簡單的栗子,來進行比較說明:
首先rdd1是一個行業基本RDD,包含ID和行業名稱,rdd2是一個行業薪水RDD,包含ID和薪水。
[plain]?view plain?copy
?
三、結果如下:
?
?
?
<span style="font-size:18px;">//下面做Join操作,預期要得到(1,×)、(2,×)、(3,×)
(2,(Hadoop,15K))
(3,(Scala,25K))
(1,(Spark,30K))
//下面做leftOutJoin操作,預期要得到(1,×)、(2,×)、(3,×)、(4,×)
(4,(Java,None))
(2,(Hadoop,Some(15K)))
(3,(Scala,Some(25K)))
(1,(Spark,Some(30K)))
//下面做rightOutJoin操作,預期要得到(1,×)、(2,×)、(3,×)、(5,×)
(2,(Some(Hadoop),15K))
(5,(None,10K))
(3,(Some(Scala),25K))
(1,(Some(Spark),30K))</span>
結果就證明了我們的預期。
總結
以上是生活随笔為你收集整理的Spark的RDD操作之Join大全的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SparkJavaAPI:join的使用
- 下一篇: spark学习:java版JavaRDD