在spark中一次遍历整个数据集?

6ovsh4lw  于 2021-05-29  发布在  Hadoop
关注(0)|答案(2)|浏览(407)

我有一个大数据集,里面有每年每个国家的人口统计数据。我在用apachespark和scala和parquet。结构为每年一列(即“1965”)。我希望能够选择跨集合的行值。
以下是模式:

columns: Array[String] = Array(country, 1960, 1961, 1962, 1963, 1964, 1965, 1966, 1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010)

我想能够过滤我的数据集的基础上人口水平,无论是哪一年。例如,当人口超过500时,获取国家名称和年份

SELECT * FROM table WHERE population > 5000000. 

Result: Cuba, 1962

如何构造Dataframe以允许这种类型的查询?

scyqe7ek

scyqe7ek1#

你只需要转动table。
以下是一篇好文章:https://databricks.com/blog/2018/11/01/sql-pivot-converting-rows-to-columns.html
如何透视Dataframe:如何透视Dataframe?

sg2wtvxw

sg2wtvxw2#

case class Demographic(country: String,
  population: Long,
  year: Int)

// Creating a strongly-typed dataset.
val dataset = Seq(
  Demographic("US",20*math.pow(10,3).toLong, 1675), 
  Demographic("US", 3*math.pow(10,8).toLong, 2018),
  Demographic("CH", math.pow(10,9).toLong, 2015))
  .toDF.as[Demographic]

// Now filtering is easy using a lambda expression.
dataset.filter(demo => demo.population > 5000)

相关问题