选择查询对大型数据集sqlcontext

时间:2019-06-02 22:17:10

标签: scala apache-spark

我的代码正在从sqlcontext读取数据。该表中有2000万条记录。我想在表中计算totalCount。

val finalresult = sqlContext.sql(“SELECT movieid,
tagname, occurrence AS eachTagCount, count AS
totalCount FROM result ORDER BY movieid”) 

我想不使用groupby来计算一列的总数并将其保存在文本文件中。 。我无需另外更改我的保存文件]

 >val sqlContext = new org.apache.spark.sql.SQLContext(sc)
    import sqlContext.implicits._
import sqlContext._
case class DataClass(UserId: Int, MovieId:Int, Tag: String)
// Create an RDD of DataClass objects and register it as a table.
val Data = sc.textFile("file:///usr/local/spark/dataset/tagupdate").map(_.split(",")).map(p => DataClass(p(0).trim.toInt, p(1).trim.toInt, p(2).trim)).toDF()
Data.registerTempTable("tag")

val orderedId = sqlContext.sql("SELECT MovieId AS Id,Tag FROM tag ORDER BY MovieId")
orderedId.rdd
  .map(_.toSeq.map(_+"").reduce(_+";"+_))
  .saveAsTextFile("/usr/local/spark/dataset/algorithm3/output")
  // orderedId.write.parquet("ordered.parquet")
val eachTagCount =orderedId.groupBy("Tag").count()
//eachTagCount.show()
eachTagCount.rdd
 .map(_.toSeq.map(_+"").reduce(_+";"+_))
 .saveAsTextFile("/usr/local/spark/dataset/algorithm3/output2")
  

错误执行程序:阶段7.0中的任务0.0中的异常(TID 604)java.lang.ArrayIndexOutOfBoundsException:在tags $$ anonfun $ 6.apply(tags.scala:46)处为1在tags $$ anonfun $ 6.apply(tags。 scala:46)在scala.collection.Iterator $$ anon $ 11.next(Iterator.scala:410)

1 个答案:

答案 0 :(得分:1)

错误NumberFormatException可能在此位置引发:

p(1).trim.toInt

将其抛出是因为您试图解析10],这显然不是有效数字。

  • 您可以尝试在文件中找到有问题的位置,然后仅删除其他]

  • 如果解析有任何问题,您也可以尝试捕获错误并提供默认值:

    import scala.util.Try
    
    Try(p(1).trim.toInt).getOrElse(0) //return 0 in case there is problem with parsing.
    
  • 您可以做的另一件事是删除要解析的字符串中不是数字的字符:

    //filter out everything which is not a digit
    p(1).filter(_.isDigit).toInt)
    

如果所有内容都被过滤掉并留下一个空字符串,它也可能会失败,因此最好将其包装在Try中。