从Scala WrappedArray提取值

时间:2018-11-13 16:37:32

标签: scala apache-spark apache-spark-mllib

我正在使用Apache Spark的ALS模型,并且welcomeForAllUsers方法返回具有模式的数据框

root
 |-- user_id: integer (nullable = false)
 |-- recommendations: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- item_id: integer (nullable = true)
 |    |    |-- rating: float (nullable = true)

实际上,建议是类似以下的WrappedArray:

WrappedArray([636958,0.32910484], [995322,0.31974298], [1102140,0.30444127], [1160820,0.27908015], [1208899,0.26943958])

我正在尝试提取 just item_ids并将其作为一维数组返回。因此,上面的示例为[636958,995322,1102140,1160820,1208899]

这就是给我带来麻烦的原因。到目前为止,我有:

    val numberOfRecs = 20
    val userRecs = model.recommendForAllUsers(numberOfRecs).cache()

    val strippedScores = userRecs.rdd.map(row => {
      val user_id = row.getInt(0)
      val recs = row.getAs[Seq[Row]](1)

      val item_ids = new Array[Int](numberOfRecs)

      recs.toArray.foreach(x => {
        item_ids :+ x.get(0)
      })

      item_ids
    })

但这只是返回[I@2f318251,如果我通过mkString(“,”)获得它的字符串值,它将返回0,0,0,0,0,0

是否有关于如何提取item_id并将其作为单独的一维数组返回的想法?

2 个答案:

答案 0 :(得分:0)

您可以使用标准名称来访问数组中的结构元素:

    scala> case class Recommendation(item_id: Int, rating: Float)
defined class Recommendation

scala> val userReqs = Seq(Array(Recommendation(636958,0.32910484f), Recommendation(995322,0.31974298f), Recommendation(1102140,0.30444127f), Recommendation(1160820,0.27908015f), Recommendation(1208899,0.26943958f))).toDF
userReqs: org.apache.spark.sql.DataFrame = [value: array<struct<item_id:int,rating:float>>]

scala> userReqs.printSchema
root
 |-- value: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- item_id: integer (nullable = false)
 |    |    |-- rating: float (nullable = false)


scala> userReqs.select("value.item_id").show(false)
+-------------------------------------------+
|item_id                                    |
+-------------------------------------------+
|[636958, 995322, 1102140, 1160820, 1208899]|
+-------------------------------------------+

scala> val ids = userReqs.select("value.item_id").collect().flatMap(_.getAs[Seq[Int]](0))
ids: Array[Int] = Array(636958, 995322, 1102140, 1160820, 1208899)

答案 1 :(得分:0)

recommendForAllUsers返回的Spark ALSModel文档中找到

  

“一个(UserCol:Int,推荐的)DataFrame,其中推荐   存储为(itemCol:Int,Rating:Float)行的数组”   (https://spark.apache.org/docs/2.2.0/api/scala/index.html#org.apache.spark.ml.recommendation.ALSModel

按数组表示,它表示WrappedArray,所以我没有尝试将其强制转换为Seq[Row],而是将其强制转换为mutable.WrappedArray[Row]。然后,我可以像这样获得每个item_id:

    val userRecItems = userRecs.rdd.map(row => {
      val user_id = row.getInt(0)
      val recs = row.getAs[mutable.WrappedArray[Row]](1)

      for (rec <- recs) {
        val item_id = rec.getInt(0)
        userRecommendatinos += game_id
      }
    })

其中userRecommendations是可变的ArrayBuffer