【问题标题】:How to iterate scala wrappedArray? (Spark)如何迭代scalawrappedArray? (火花)
【发布时间】:2018-07-18 13:00:06
【问题描述】:

我执行以下操作:

val tempDict = sqlContext.sql("select words.pName_token,collect_set(words.pID) as docids 
                               from words
                               group by words.pName_token").toDF()

val wordDocs = tempDict.filter(newDict("pName_token")===word)

val listDocs = wordDocs.map(t => t(1)).collect()

listDocs: Array

[Any] = Array(WrappedArray(123, 234, 205876618, 456))

我的问题是如何遍历这个包装数组或将其转换为列表?

我为listDocs 得到的选项是applyasInstanceOfcloneisInstanceOflengthtoStringupdate

我该如何进行?

【问题讨论】:

    标签: scala apache-spark apache-spark-sql


    【解决方案1】:

    这是解决此问题的一种方法。

    import org.apache.spark.sql.Row
    import org.apache.spark.sql.functions._
    import scala.collection.mutable.WrappedArray
    
    val data = Seq((Seq(1,2,3),Seq(4,5,6),Seq(7,8,9)))
    val df = sqlContext.createDataFrame(data)
    val first = df.first
    
    // use a pattern match to deferral the type
    val mapped = first.getAs[WrappedArray[Int]](0)
    
    // now we can use it like normal collection
    mapped.mkString("\n")
    
    // get rows where has array
    val rows = df.collect.map {
        case Row(a: Seq[Any], b: Seq[Any], c: Seq[Any]) => 
            (a, b, c)
    }
    rows.mkString("\n")
    

    【讨论】:

    • 实际上我这样做了,这似乎解决了我的情况: val arrDocs = listDocs(0) val temp = arrDocs.asInstanceOf[mutable.WrappedArray[Long]] temp现在基本上给了我一个迭代器。
    • 感谢@boY,我更新了答案。上一个有点冗长。
    • 我的代码中的 WrappedArray 有问题,可以用 Seq[Int] 替换它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多