DataFrame 提供了一个 DSL(domain-specific language)用于在 Scala,Java,Python 或者 R 中的结构化数据操作。
正如上面提到的一样,Spark 2.0 中 DataFrame 在 Scala 和 JavaAPI 中仅仅是多个 Row(行)的 Dataset 。这些操作也参考了与强类型的 Scala/Java Datasets 的 “类型转换” 相对应的 “无类型转换”。
这里包括一些使用 Dataset 进行结构化数据处理的示例 :
// This import is needed to use the $-notation import spark.implicits._ // Print the schema in a tree format df.printSchema() // root // |-- age: long (nullable = true) // |-- name: string (nullable = true) // Select only the "name" column df.select("name").show() // +-------+ // | name| // +-------+ // |Michael| // | Andy| // | Justin| // +-------+ // Select everybody, but increment the age by 1 df.select($"name", $"age" + 1).show() // +-------+---------+ // | name|(age + 1)| // +-------+---------+ // |Michael| null| // | Andy| 31| // | Justin| 20| // +-------+---------+ // Select people older than 21 df.filter($"age" > 21).show() // +---+----+ // |age|name| // +---+----+ // | 30|Andy| // +---+----+ // Count people by age df.groupBy("age").count().show() // +----+-----+ // | age|count| // +----+-----+ // | 19| 1| // |null| 1| // | 30| 1| // +----+-----+ // 所有的示例代码可以在 Spark repo 的 “examples/src/main/scala/org/apache/spark/examples/sql/SparkSQLExample.scala” 中找到。
能够在 DataFrame 上被执行的操作类型的完整列表请参考 API 文档。
除了简单的列引用和表达式之外,DataFrame 也有丰富的函数库,包括 string 操作,date 算术,常见的 math 操作以及更多。可用的完整列表请参考 DataFrame 函数参考。