如何通过映射结果过滤Spark RDD?

时间:2019-02-09 18:37:43

标签: scala apache-spark filter

我需要通过映射结果过滤RDD。 最初我有RDD诊断:

诊断(000140966-01,2008-07-06,250.00) 诊断(202009464-01,2009-09-29,V70.0) 诊断(202009464-01,2009-09-29,590.80) 诊断(818009099-01,2014-12-11,592.0) 诊断(545360000-01,2005-12-09,584.9) 诊断(000012631-01,2013-09-23,V70.0) 诊断(666071437-01,2006-11-29,496) 诊断(000681687-01,2006-06-28,250.01) 诊断(497910000-01,2009-04-07,584.9) 诊断(022001344-01,2011-11-28,584.9) 诊断(285060000-01,2012-03-28,584.9) ....

其中:  案例类Diagnostic(PatientID:字符串,日期:日期,代码:字符串)

我将患者分组:

val grouped_patients = diagnostic.groupBy(_.patientID)
grouped_patients.take(50).foreach(println)

(000644947-01,CompactBuffer(诊断(000644947-01,2010-09-22,584.9),诊断(000644947-01,2007-02-02,584.9),诊断(000644947-01,2014-06-15,250.01),诊断(000644947-01,2009-01-02,250.01),...)) (000124665-01,CompactBuffer(诊断(000124665-01,2006-09-05,V70.0),诊断(000124665-01,2011-11-21,585.9),诊断(000124665-01,2009-10-14,585.9), ....))

我需要使用一些特定的代码(我有一组这些代码T1DM_DX)过滤掉患者。

我可以伸出手来

val grouped_patient_fil_1 = diagnostic.groupBy(_.patientID)
    .map(x => x._2.map(y => y.code))
    .map(x=>x.toSet.intersect(T1DM_DX).size>0)
    .take(100).foreach(println)

... 假 假 假 真正 假 真正 假 真正 假 假 假 ....

如何过滤具有“ True”的“分组患者”? 我认为应该是这样:

val grouped_patient_fil_1 = grouped_patients
    .filter(x => x._2.map(y => y.code)
          .map(x=> x.toSet.intersect(T1DM_DX).size>0))

但是我遇到一个错误:

T2dmPhenotype.scala:71:37: type mismatch;
[error]  found   : scala.collection.immutable.Set[String]
[error]  required: scala.collection.GenSet[Any]
[error] Note: String <: Any, but trait GenSet is invariant in type A.
[error] You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
[error]         .map(x => x.toSet.intersect(T1DM_DX).size > 0))

1 个答案:

答案 0 :(得分:1)

如果您已经有一个包含Boolean个对象的数组,则只需将map更改为流中的filter,将只保留真实值:

val grouped_patient_fil_1 = diagnostic
    .groupBy(_.patientID)
    .filter(x => x._2.map(y => y.code).toSet.intersect(T1DM_DX).size>0)
grouped_patient_fil_1.take(100).foreach(println)