JSONObjectEachRow 형식
JSONObjectEachRow 형식
JSONObjectEachRow 형식은 모든 데이터를 단일 JSON 객체로 표현하며, 각 행은 이 객체의 별도 필드로 표현돼요(JSONEachRow 형식과 유사해요). 객체 이름을 컬럼 값으로 사용하려면 format_json_object_each_row_column_for_object_name 특수 설정을 사용할 수 있습니다.
출처: 문서
본문
| Input | Output | Alias |
|---|---|---|
| ✔ | ✔ |
설명 (Description)
이 형식에서는 모든 데이터가 단일 JSON Object로 표현되며, 각 행은 JSONEachRow 형식과 유사하게 이 객체의 별도 필드로 표현됩니다.
사용 예시 (Example usage)
기본 예시 (Basic example)
다음과 같은 JSON이 있다고 할게요:
{
"row_1": {"num": 42, "str": "hello", "arr": [0,1]},
"row_2": {"num": 43, "str": "hello", "arr": [0,1,2]},
"row_3": {"num": 44, "str": "hello", "arr": [0,1,2,3]}
}
객체 이름을 컬럼 값으로 사용하려면 format_json_object_each_row_column_for_object_name 특수 설정을 사용할 수 있습니다. 이 설정의 값은 결과 객체에서 행의 JSON 키로 사용되는 컬럼 이름으로 설정됩니다.
출력 (Output)
두 개의 컬럼을 가진 test 테이블이 있다고 해 볼게요:
┌─object_name─┬─number─┐
│ first_obj │ 1 │
│ second_obj │ 2 │
│ third_obj │ 3 │
└─────────────┴────────┘
JSONObjectEachRow 형식으로 출력하고 format_json_object_each_row_column_for_object_name 설정을 사용해 볼게요:
Query``` SELECT * FROM test SETTINGS format_json_object_each_row_column_for_object_name='object_name'
Response```
{
"first_obj": {"number": 1},
"second_obj": {"number": 2},
"third_obj": {"number": 3}
}
입력 (Input)
이전 예시의 출력을 data.json 파일에 저장했다고 해 볼게요:
Query``` SELECT * FROM file('data.json', JSONObjectEachRow, 'object_name String, number UInt64') SETTINGS format_json_object_each_row_column_for_object_name='object_name'
Response```
┌─object_name─┬─number─┐
│ first_obj │ 1 │
│ second_obj │ 2 │
│ third_obj │ 3 │
└─────────────┴────────┘
스키마 추론에서도 동작합니다:
Query``` DESCRIBE file('data.json', JSONObjectEachRow) SETTING format_json_object_each_row_column_for_object_name='object_name'
Response```
┌─name────────┬─type────────────┐
│ object_name │ String │
│ number │ Nullable(Int64) │
└─────────────┴─────────────────┘
데이터 삽입 (Inserting data)
Query``` INSERT INTO UserActivity FORMAT JSONEachRow {"PageViews":5, "UserID":"4324182021466249494", "Duration":146,"Sign":-1} {"UserID":"4324182021466249494","PageViews":6,"Duration":185,"Sign":1}
ClickHouse는 다음을 허용합니다:
- 객체에서 키-값 쌍의 임의 순서.
- 일부 값 생략.
ClickHouse는 요소 사이의 공백과 객체 뒤의 쉼표를 무시합니다. 모든 객체를 한 줄에 전달할 수 있으며, 줄 바꿈으로 구분할 필요가 없습니다.
#### 생략된 값 처리 (Omitted values processing)
ClickHouse는 생략된 값을 해당 데이터 타입의 기본값으로 대체합니다. DEFAULT expr이 지정된 경우 ClickHouse는 input_format_defaults_for_omitted_fields 설정에 따라 다른 대체 규칙을 사용합니다. 다음 테이블을 고려해 볼게요:
Query```
CREATE TABLE IF NOT EXISTS example_table
(
x UInt32,
a DEFAULT x * 2
) ENGINE = Memory;
input_format_defaults_for_omitted_fields = 0이면x와a의 기본값은0입니다(UInt32데이터 타입의 기본값).input_format_defaults_for_omitted_fields = 1이면x의 기본값은0이지만,a의 기본값은x * 2입니다.
input_format_defaults_for_omitted_fields = 1로 데이터를 삽입하면 0일 때보다 더 많은 컴퓨팅 자원을 소비합니다.
데이터 선택 (Selecting data)
UserActivity 테이블을 예로 들어 볼게요:
┌──────────────UserID─┬─PageViews─┬─Duration─┬─Sign─┐
│ 4324182021466249494 │ 5 │ 146 │ -1 │
│ 4324182021466249494 │ 6 │ 185 │ 1 │
└─────────────────────┴───────────┴──────────┴──────┘
쿼리 SELECT * FROM UserActivity FORMAT JSONEachRow는 다음을 반환합니다:
{"UserID":"4324182021466249494","PageViews":5,"Duration":146,"Sign":-1}
{"UserID":"4324182021466249494","PageViews":6,"Duration":185,"Sign":1}
JSON 형식과 달리 잘못된 UTF-8 시퀀스 대체는 없습니다. 값은 JSON과 같은 방식으로 이스케이프됩니다. 문자열에는 어떤 바이트 집합도 출력될 수 있습니다. 테이블의 데이터가 정보를 잃지 않고 JSON으로 형식화될 수 있다고 확신한다면 JSONEachRow 형식을 사용하세요.
중첩 구조 사용 (Usage of Nested Structures)
Nested 데이터 타입 컬럼이 있는 테이블이 있다면 동일한 구조의 JSON 데이터를 삽입할 수 있습니다. 이 기능은 input_format_import_nested_json 설정으로 활성화합니다. 예를 들어 다음 테이블을 고려해 볼게요:
Query``` CREATE TABLE json_each_row_nested (n Nested (s String, i Int32) ) ENGINE = Memory
Nested 데이터 타입 설명에서 볼 수 있듯이 ClickHouse는 중첩 구조의 각 컴포넌트를 별도의 컬럼(우리 테이블에서는 n.s와 n.i)으로 취급합니다. 다음과 같은 방식으로 데이터를 삽입할 수 있어요:
Query```
INSERT INTO json_each_row_nested FORMAT JSONEachRow {"n.s": ["abc", "def"], "n.i": [1, 23]}
계층적 JSON 객체로 데이터를 삽입하려면 input_format_import_nested_json=1로 설정하세요.
{
"n": {
"s": ["abc", "def"],
"i": [1, 23]
}
}
이 설정이 없으면 ClickHouse는 예외를 던집니다.
Query``` SELECT name, value FROM system.settings WHERE name = 'input_format_import_nested_json'
Response```
┌─name────────────────────────────┬─value─┐
│ input_format_import_nested_json │ 0 │
└─────────────────────────────────┴───────┘
Query``` INSERT INTO json_each_row_nested FORMAT JSONEachRow {"n": {"s": ["abc", "def"], "i": [1, 23]}}
Response```
Code: 117. DB::Exception: Unknown field found while parsing JSONEachRow format: n: (at row 1)
Query``` SET input_format_import_nested_json=1 INSERT INTO json_each_row_nested FORMAT JSONEachRow {"n": {"s": ["abc", "def"], "i": [1, 23]}} SELECT * FROM json_each_row_nested
Response```
┌─n.s───────────┬─n.i────┐
│ ['abc','def'] │ [1,23] │
└───────────────┴────────┘
형식 설정 (Format settings)
| Setting | Description | Default | Notes |
|---|---|---|---|
| input_format_import_nested_json | map nested JSON data to nested tables (it works for JSONEachRow format). | false | |
| input_format_json_read_bools_as_numbers | allow to parse bools as numbers in JSON input formats. | true | |
| input_format_json_read_bools_as_strings | allow to parse bools as strings in JSON input formats. | true | |
| input_format_json_read_numbers_as_strings | allow to parse numbers as strings in JSON input formats. | true | |
| input_format_json_read_arrays_as_strings | allow to parse JSON arrays as strings in JSON input formats. | true | |
| input_format_json_read_objects_as_strings | allow to parse JSON objects as strings in JSON input formats. | true | |
| input_format_json_named_tuples_as_objects | parse named tuple columns as JSON objects. | true | |
| input_format_json_try_infer_numbers_from_strings | try to infer numbers from string fields while schema inference. | false | |
| input_format_json_try_infer_named_tuples_from_objects | try to infer named tuple from JSON objects during schema inference. | true | |
| input_format_json_infer_incomplete_types_as_strings | use type String for keys that contains only Nulls or empty objects/arrays during schema inference in JSON input formats. | true | |
| input_format_json_defaults_for_missing_elements_in_named_tuple | insert default values for missing elements in JSON object while parsing named tuple. | true | |
| input_format_json_ignore_unknown_keys_in_named_tuple | ignore unknown keys in json object for named tuples. | false | |
| input_format_json_compact_allow_variable_number_of_columns | allow variable number of columns in JSONCompact/JSONCompactEachRow format, ignore extra columns and use default values on missing columns. | false | |
| input_format_json_throw_on_bad_escape_sequence | throw an exception if JSON string contains bad escape sequence. If disabled, bad escape sequences will remain as is in the data. | true | |
| input_format_json_empty_as_default | treat empty fields in JSON input as default values. | false . | For complex default expressions input_format_defaults_for_omitted_fields must be enabled too. |
| output_format_json_quote_64bit_integers | controls quoting of 64-bit integers in JSON output format. | true | |
| output_format_json_quote_64bit_floats | controls quoting of 64-bit floats in JSON output format. | false | |
| output_format_json_quote_denormals | enables '+nan', '-nan', '+inf', '-inf' outputs in JSON output format. | false | |
| output_format_json_quote_decimals | controls quoting of decimals in JSON output format. | false | |
| output_format_json_escape_forward_slashes | controls escaping forward slashes for string outputs in JSON output format. | true | |
| output_format_json_named_tuples_as_objects | serialize named tuple columns as JSON objects. | true | |
| output_format_json_array_of_rows | output a JSON array of all rows in JSONEachRow(Compact) format. | false | |
| output_format_json_validate_utf8 | enables validation of UTF-8 sequences in JSON output formats (note that it doesn't impact formats JSON/JSONCompact/JSONColumnsWithMetadata, they always validate utf8). | false |