我在 hadoop 中有一个文本文件,我需要使用 spark java api 使用它的第二列对其进行排序。我正在使用数据框,但我不确定它的列。 它可能有动态列,这意味着我不知道确切的列数。
我该如何继续?请帮助我。
提前致谢。
最佳答案
首先我想在 scala(不是 java)中给出一个 csv 示例
您可以使用 Spark csv api 创建数据框并根据您想要的任何列进行排序。 如果您有任何限制,请参阅以下方式。
固定列数:
从下面的固定列数示例开始...... 你可以按照这个例子。
ebay.csv 的数据看起来像:
“8213034705,95,2.927373,jake7870,0,95,117.5,xbox,3”
// SQLContext entry point for working with structured data
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
// this is used to implicitly convert an RDD to a DataFrame.
import sqlContext.implicits._
// Import Spark SQL data types and Row.
import org.apache.spark.sql._
//define the schema using a case class
case class Auction(auctionid: String, bid: Float, bidtime: Float, bidder: String, bidderrate: Integer, openbid: Float, price: Float, item: String, daystolive: Integer)
val auction = sc.textFile("ebay.csv").map(_.split(",")).map(p =>
Auction(p(0),p(1).toFloat,p(2).toFloat,p(3),p(4).toInt,p(5).toFloat,p(6).toFloat,p(7),p(8).toInt )).toDF()
// Display the top 20 rows of DataFrame
auction.show()
// auctionid bid bidtime bidder bidderrate openbid price item daystolive
// 8213034705 95.0 2.927373 jake7870 0 95.0 117.5 xbox 3
// 8213034705 115.0 2.943484 davidbresler2 1 95.0 117.5 xbox 3 …
// Return the schema of this DataFrame
auction.printSchema()
root
|-- auctionid: string (nullable = true)
|-- bid: float (nullable = false)
|-- bidtime: float (nullable = false)
|-- bidder: string (nullable = true)
|-- bidderrate: integer (nullable = true)
|-- openbid: float (nullable = false)
|-- price: float (nullable = false)
|-- item: string (nullable = true)
|-- daystolive: integer (nullable = true)
auction.sort("auctionid") // this will sort first column i.e auctionid
列数可变(since Case
class with Array parameter is possible):
你可以像下面这样使用伪代码,其中前 4 个元素是固定的,剩下的都是可变数组......
由于您只是插入以对第二列进行排序,因此这会起作用,并且所有其他数据都将存在于该特定行的数组中,以供以后使用。
case class Auction(auctionid: String, bid: Float, bidtime: Float, bidder: String, variablenumberofColumnsArray:String*)
val auction = sc.textFile("ebay.csv").map(_.split(",")).map(p =>
Auction(p(0),p(1).toFloat,p(2).toFloat,p(3),p(4).toInt, VariableNumberOfColumnsArray or any complex type like Map ).toDF()
auction.sort("auctionid") // this will sort first column i.e auctionid
关于java - 如何在不知道数据模式的情况下将数据从文本文件加载到 spark 数据框中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40605012/