Spark 1.2 を使用している場合は、次のことができます (Scala を使用)...
使用するフィールドがすでにわかっている場合は、これらのフィールドのスキーマを作成し、このスキーマを JSON データセットに適用できます。Spark SQL は SchemaRDD を返します。次に、それを登録してテーブルとしてクエリできます。ここにスニペットがあります...
// sc is an existing SparkContext.
val sqlContext = new org.apache.spark.sql.hive.HiveContext(sc)
// The schema is encoded in a string
val schemaString = "name gender"
// Import Spark SQL data types.
import org.apache.spark.sql._
// Generate the schema based on the string of schema
val schema =
StructType(
schemaString.split(" ").map(fieldName => StructField(fieldName, StringType, true)))
// Create the SchemaRDD for your JSON file "people" (every line of this file is a JSON object).
val peopleSchemaRDD = sqlContext.jsonFile("people.txt", schema)
// Check the schema of peopleSchemaRDD
peopleSchemaRDD.printSchema()
// Register peopleSchemaRDD as a table called "people"
peopleSchemaRDD.registerTempTable("people")
// Only values of name and gender fields will be in the results.
val results = sqlContext.sql("SELECT * FROM people")
peopleSchemaRDD のスキーマ (peopleSchemaRDD.printSchema()) を見ると、名前と性別のフィールドだけが表示されます。
または、データセットを調べて、すべてのフィールドを確認した後で必要なフィールドを決定したい場合は、Spark SQL にスキーマの推測を依頼できます。次に、SchemaRDD をテーブルとして登録し、プロジェクションを使用して不要なフィールドを削除できます。ここにスニペットがあります...
// Spark SQL will infer the schema of the given JSON file.
val peopleSchemaRDD = sqlContext.jsonFile("people.txt")
// Check the schema of peopleSchemaRDD
peopleSchemaRDD.printSchema()
// Register peopleSchemaRDD as a table called "people"
peopleSchemaRDD.registerTempTable("people")
// Project name and gender field.
sqlContext.sql("SELECT name, gender FROM people")