【问题标题】:how to convert a RDD to other RDD using case class property?如何使用案例类属性将 RDD 转换为其他 RDD?
【发布时间】:2020-03-05 05:54:37
【问题描述】:

我有一个如下名称的 RDD:other_nodes

(4,(1,true))
(22,(1,true))
(14,(1,true))
(3,(1,true))
(8,(1,true))
(18,(1,true))

我写了一个如下的案例类并将其应用到图表上,它给出了我想要的结果:

case class nodes_properties(label:Int, isVisited:Boolean=false)

当我在图表上应用案例时,其结果如下所示:

(1,nodes_properties(15,false))
(2,nodes_properties(11,false))
(3,nodes_properties(9,false))

问题:如何在 other_nodes RDD 上应用我定义的案例类以获得如下结果:

(4,nodes_properties(1,true))
(22,nodes_properties(1,true))
(14,nodes_properties(1,true))
(3,nodes_properties(1,true))
(8,nodes_properties(1,true))
(18,nodes_properties(1,true))

【问题讨论】:

    标签: scala apache-spark


    【解决方案1】:

    此解决方案可能有效:

    scala> val data = sc.parallelize(Seq((4,(1, true)),(22,(1,true))))
    data: org.apache.spark.rdd.RDD[(Int, (Int, Boolean))] = ParallelCollectionRDD[72] at parallelize at <console>:39
    
    scala> data.take(2)
    res27: Array[(Int, (Int, Boolean))] = Array((4,(1,true)), (22,(1,true)))
    
    scala> val data1 = data.map(elem => (elem._1, nodes_properties(elem._2._1, elem._2._2)))
    data1: org.apache.spark.rdd.RDD[(Int, nodes_properties)] = MapPartitionsRDD[73] at map at <console>:42
    
    scala> data1.take(2)
    res28: Array[(Int, nodes_properties)] = Array((4,nodes_properties(1,true)), (22,nodes_properties(1,true)))
    

    编辑

    问题是others_rdd 中的每个元素都是(VertexId, Any) 类型。您需要转换为 (VertexId, (Int, Boolean)) 类型才能应用您的案例类。这样做的方法是

    val newRdd = others_rdd.map(elem => (elem._1, elem._2.asInstanceOf[(Int,Boolean)]))
    

    执行此操作后,您可以通过映射到node_properties 类来应用如上所示的解决方案。

    如果有帮助请告诉我!!

    【讨论】:

    • 感谢您的回复。我想你提到了确切的方法。但有一个小问题。我不知道为什么在 data.map(elem =&gt; (elem._1, nodes_properties(elem._2._1, elem._2._2))) elem._2._1elem._2._2 会出错。我的 RDD 的课程是:class org.apache.spark.rdd.MapPartitionsRDD
    • 你在others_rdd.take(1)时能告诉我类型吗?
    • 我使用 intellij 并将类型显示为:``` val x: Array[(VertexId, Any)] =other_RDD.take(1) ``` 当我使用 println(x.getClass) 时结果是class [Lscala.Tuple2;
    • 我做了一些join和mapvalues操作,最后other_rdd是它们的结果
    • 我已经更新了解决方案。让我知道是否有帮助!
    猜你喜欢
    • 2021-09-27
    • 1970-01-01
    • 2016-08-28
    • 2023-02-24
    • 2014-11-28
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    相关资源
    最近更新 更多