JSON ファイル
Spark SQL は自動的にJSONデータセットのスキーマを推測しDataset[Row]
としてロードすることができます。この変換は、Dataset[String]
あるいはJSONファイルのどちらかでSparkSession.read.json()
を使って行うことができます。
json ファイルとして提供されるファイルは一般的なJSONファイルではないことに注意してください。各行は別個の自己内包の有効なJSONオブジェクトでなければなりません。 更に詳しい情報は、JSON Lines text format, also called newline-delimited JSONを見てください。
通常の複数行のJSONファイルについては、multiLine
オプションをtrue
に設定します。
// Primitive types (Int, String, etc) and Product types (case classes) encoders are
// supported by importing this when creating a Dataset.
import spark.implicits._
// A JSON dataset is pointed to by path.
// The path can be either a single text file or a directory storing text files
val path = "examples/src/main/resources/people.json"
val peopleDF = spark.read.json(path)
// The inferred schema can be visualized using the printSchema() method
peopleDF.printSchema()
// root
// |-- age: long (nullable = true)
// |-- name: string (nullable = true)
// Creates a temporary view using the DataFrame
peopleDF.createOrReplaceTempView("people")
// SQL statements can be run by using the sql methods provided by spark
val teenagerNamesDF = spark.sql("SELECT name FROM people WHERE age BETWEEN 13 AND 19")
teenagerNamesDF.show()
// +------+
// | name|
// +------+
// |Justin|
// +------+
// Alternatively, a DataFrame can be created for a JSON dataset represented by
// a Dataset[String] storing one JSON object per string
val otherPeopleDataset = spark.createDataset(
"""{"name":"Yin","address":{"city":"Columbus","state":"Ohio"}}""" :: Nil)
val otherPeople = spark.read.json(otherPeopleDataset)
otherPeople.show()
// +---------------+----+
// | address|name|
// +---------------+----+
// |[Columbus,Ohio]| Yin|
// +---------------+----+
Spark SQL は自動的にJSONデータセットのスキーマを推測しDataset<Row>
としてロードすることができます。この変換は、Dataset<String>
あるいはJSONファイルのどちらかでSparkSession.read().json()
を使って行うことができます。
json ファイルとして提供されるファイルは一般的なJSONファイルではないことに注意してください。各行は別個の自己内包の有効なJSONオブジェクトでなければなりません。 更に詳しい情報は、JSON Lines text format, also called newline-delimited JSONを見てください。
通常の複数行のJSONファイルについては、multiLine
オプションをtrue
に設定します。
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
// A JSON dataset is pointed to by path.
// The path can be either a single text file or a directory storing text files
Dataset<Row> people = spark.read().json("examples/src/main/resources/people.json");
// The inferred schema can be visualized using the printSchema() method
people.printSchema();
// root
// |-- age: long (nullable = true)
// |-- name: string (nullable = true)
// Creates a temporary view using the DataFrame
people.createOrReplaceTempView("people");
// SQL statements can be run by using the sql methods provided by spark
Dataset<Row> namesDF = spark.sql("SELECT name FROM people WHERE age BETWEEN 13 AND 19");
namesDF.show();
// +------+
// | name|
// +------+
// |Justin|
// +------+
// Alternatively, a DataFrame can be created for a JSON dataset represented by
// a Dataset<String> storing one JSON object per string.
List<String> jsonData = Arrays.asList(
"{\"name\":\"Yin\",\"address\":{\"city\":\"Columbus\",\"state\":\"Ohio\"}}");
Dataset<String> anotherPeopleDataset = spark.createDataset(jsonData, Encoders.STRING());
Dataset<Row> anotherPeople = spark.read().json(anotherPeopleDataset);
anotherPeople.show();
// +---------------+----+
// | address|name|
// +---------------+----+
// |[Columbus,Ohio]| Yin|
// +---------------+----+
Spark SQL は自動的にJSONデータセットのスキーマを推測しデータフレームとしてロードすることができます。この変換は、JSONファイル上のSparkSession.read.json
を使って行うことができます。
json ファイルとして提供されるファイルは一般的なJSONファイルではないことに注意してください。各行は別個の自己内包の有効なJSONオブジェクトでなければなりません。 更に詳しい情報は、JSON Lines text format, also called newline-delimited JSONを見てください。
通常の複数行のJSONファイルについては、multiLine
パラメータをTrue
に設定します。
# spark is from the previous example.
sc = spark.sparkContext
# A JSON dataset is pointed to by path.
# The path can be either a single text file or a directory storing text files
path = "examples/src/main/resources/people.json"
peopleDF = spark.read.json(path)
# The inferred schema can be visualized using the printSchema() method
peopleDF.printSchema()
# root
# |-- age: long (nullable = true)
# |-- name: string (nullable = true)
# Creates a temporary view using the DataFrame
peopleDF.createOrReplaceTempView("people")
# SQL statements can be run by using the sql methods provided by spark
teenagerNamesDF = spark.sql("SELECT name FROM people WHERE age BETWEEN 13 AND 19")
teenagerNamesDF.show()
# +------+
# | name|
# +------+
# |Justin|
# +------+
# Alternatively, a DataFrame can be created for a JSON dataset represented by
# an RDD[String] storing one JSON object per string
jsonStrings = ['{"name":"Yin","address":{"city":"Columbus","state":"Ohio"}}']
otherPeopleRDD = sc.parallelize(jsonStrings)
otherPeople = spark.read.json(otherPeopleRDD)
otherPeople.show()
# +---------------+----+
# | address|name|
# +---------------+----+
# |[Columbus,Ohio]| Yin|
# +---------------+----+
Spark SQL は自動的にJSONデータセットのスキーマを推測しデータフレームとしてロードすることができます。read.json()
を使うと、データを各ファイルの各行がJSONオブジェクトであるJSONファイルのディレクトリからデータをロードします。
json ファイルとして提供されるファイルは一般的なJSONファイルではないことに注意してください。各行は別個の自己内包の有効なJSONオブジェクトでなければなりません。 更に詳しい情報は、JSON Lines text format, also called newline-delimited JSONを見てください。
通常の複数行のJSONファイルについては、名前付きパラメータmultiLine
をTRUE
に設定します。
# A JSON dataset is pointed to by path.
# The path can be either a single text file or a directory storing text files.
path <- "examples/src/main/resources/people.json"
# Create a DataFrame from the file(s) pointed to by path
people <- read.json(path)
# The inferred schema can be visualized using the printSchema() method.
printSchema(people)
## root
## |-- age: long (nullable = true)
## |-- name: string (nullable = true)
# Register this DataFrame as a table.
createOrReplaceTempView(people, "people")
# SQL statements can be run by using the sql methods.
teenagers <- sql("SELECT name FROM people WHERE age >= 13 AND age <= 19")
head(teenagers)
## name
## 1 Justin
データソース オプション
JSONのデータソースオプションは、次のものを使って設定することができます:
- the
.option
/.options
methods ofDataFrameReader
DataFrameWriter
DataStreamReader
DataStreamWriter
- the built-in functions below
from_json
to_json
schema_of_json
- CREATE TABLE USING DATA_SOURCEの
OPTIONS
句
プロパティ名 | デフォルト | 意味 | スコープ |
---|---|---|---|
timeZone |
(spark.sql.session.timeZone 設定の値) |
JSONデータソースまたはパーティション値のタイムスタンプの形式に使われるタイムゾーンIDを示す文字列を設定します。次の形式のtimeZone がサポートされています:
|
read/write |
primitivesAsString |
false |
全てのプリミティブ値を文字列型として推測します。 | read |
prefersDecimal |
false |
全ての浮動小数点値を10進数として推測します。値が10進数に収まらない場合は、doubleとして推測されます。 | read |
allowComments |
false |
JSONレコードのJava/C++スタイルのコメントを無視します。 | read |
allowUnquotedFieldNames |
false |
引用符で囲まれていないJSONフィールド名を許可します。 | read |
allowSingleQuotes |
true |
二重引用符に加えて一重引用符を許可します。 | read |
allowNumericLeadingZero |
false |
数値の先行0を許可します (例 00012)。 | read |
allowBackslashEscapingAnyCharacter |
false |
バックスラッシュ引用符メカニズムを使って、全ての文字の引用符を受け入れることができます。 | read |
モード |
PERMISSIVE |
解析中に破損したレコードを処理するためのモードを許可します。
|
read |
columnNameOfCorruptRecord |
(spark.sql.columnNameOfCorruptRecord 設定の値) |
PERMISSIVE モードで作成された不正な形式の文字列を持つ新しいフィールドの名前を変更できます。これは spark.sql.columnNameOfCorruptRecord を上書きします。 |
read |
dateFormat |
yyyy-MM-dd |
日付フォーマットを示す文字列を設定します。独自の日付形式は、 datetimeパターンの形式に従います。これは日付型に適用されます。 | read/write |
timestampFormat |
yyyy-MM-dd'T'HH:mm:ss[.SSS][XXX] |
タイムスタンプフォーマットを示す文字列を設定します。独自の日付形式は、 datetimeパターンの形式に従います。これはタイムスタンプ型に適用されます。 | read/write |
multiLine |
false |
ファイルごとに複数行にまたがる可能性のあるレコードを解析します。 | read |
allowUnquotedControlChars |
false |
JSON文字列に引用符で囲まれていない制御文字(タブおよび改行文字を含む、値が32未満のASCII文字)を含めるかどうかを許可します。 | read |
encoding |
multiLine がtrue (読み込み用)、UTF-8 (書き込み用)に設定されている場合に自動的に検出します。 |
読み込みの場合、JSONファイルの標準の基本エンコーディングまたは拡張エンコーディングのいずれかを強制的に設定できます。例えば、UTF-16BE、UTF-32LE。書き込みの場合、保存されたjsonファイルのエンコーディング(文字セット)を指定します。 | read/write |
lineSep |
\r , \r\n , \n (読み込み用), \n (書き込み用) |
解析に使う行区切り文字を定義します。 | read/write |
samplingRatio |
1.0 |
スキーマ推測に使われる入力JSONオブジェクトの割合を定義します。 | read |
dropFieldIfAllNull |
false |
スキーマ推測中に全てのnull値の列を無視するか、空の配列/構造体を無視するかどうか。 | read |
locale |
en-US |
ロケールをIETF BCP 47形式の言語タグとして設定します。例えば、locale は日付とタイムスタンプの解析中に使われます。 |
read |
allowNonNumericNumbers |
true |
JSONパーサーが“Not-a-Number” (NaN) トークンのセットを正当な浮動小数点値として認識できるようにします。
|
read |
圧縮 |
(none) | ファイルに保存する時に使う圧縮コーディック。大文字と小文字を区別しない既知の短縮名の1つです(none, bzip2, gzip, lz4, snappy, deflate)。 | write |
ignoreNullFields |
(spark.sql.jsonGenerator.ignoreNullFields 設定の値) |
JSONオブジェクトを生成する時に、nullフィールドを無視するかどうか。 | write |
その他の汎用オプションは、汎用ファイルソースオプションにあります。