G.4. Чтение JSON-файлов (read_json) #

Требуемые права: суперпользователь или администратор Postgres Pro AXE.

За подробной информацией об управлении доступом обратитесь к Главе 17.

Выполните следующую команду на сервере Postgres Pro AXE:

  SELECT * FROM read_json('путь', необязательные_параметры);
  

Здесь:

  • путь: путь к JSON-файлам, которые требуется прочитать.

    Вы можете указать значение в одном из следующих форматов:

    • путь к JSON-файлу, например 'file.json';

    • шаблон glob, например 'data/*.json';

    • массив путей, например ['file1.json', 'file2.json'].

  • необязательные_параметры: необязательные параметры, указанные в формате параметр := значение.

    Доступные параметры:

    • compression: способ сжатия файлов.

      Возможные значения:

      • auto_detect;

      • none;

      • gzip;

      • zstd.

      Значение по умолчанию: auto_detect — способ сжатия определяется автоматически с помощью расширений файлов.

    • filename: указывает, следует ли возвращать столбец filename с путями к файлам. Начиная с DuckDB v1.3.0, этот столбец добавляется автоматически.

      Возможные значения:

      • true;

      • false.

      Значение по умолчанию: false.

    • format: формат JSON.

      Возможные значения:

      • auto;

      • unstructured;

      • newline_delimited;

      • array.

      Значение по умолчанию: array.

    • hive_partitioning: указывает, связан ли каталог с секционированной аналитической таблицей и следует ли возвращать столбцы секций.

      Возможные значения:

      • true;

      • false.

      Значение по умолчанию: определяется автоматически на основе структуры каталогов.

      За подробной информацией о Hive-секционировании обратитесь к Разделу 15.2.

    • ignore_errors: указывает, следует ли игнорировать ошибки разбора.

      Возможные значения:

      • true;

      • false.

      Этот параметр применяется, только если для параметра format указано значение newline_delimited.

      Значение по умолчанию: false.

    • maximum_sample_files: максимальное количество JSON-файлов, выбираемых для автоматического определения имён столбцов и типов данных.

      Количество JSON-объектов, выбираемых в каждом файле, можно указать вручную с помощью параметра sample_size.

      Значение по умолчанию: 32.

    • maximum_object_size: максимальный размер JSON-объекта в байтах.

      Значение по умолчанию: 16777216.

    • auto_detect: указывает, следует ли автоматически определять имена столбцов и типы данных.

      Возможные значения:

      • true;

      • false.

      Значение по умолчанию: true.

    • dateformat: формат, используемый при разборе дат.

      Значение по умолчанию: iso.

    • maximum_depth: максимальная глубина вложенности для автоматического определения имён столбцов и типов данных.

      Значение по умолчанию: -1 — глубина вложенности не ограничена.

    • records: указывает, следует ли возвращать JSON-объекты в виде отдельных столбцов.

      Возможные значения:

      • auto;

      • true;

      • false.

      Если для этого параметра указано значение false, каждый JSON-объект возвращается в виде значения STRUCT.

      Значение по умолчанию: auto.

    • sample_size: количество JSON-объектов, выбираемых в каждом файле для автоматического определения имён столбцов и типов данных.

      Количество выбираемых JSON-файлов можно указать вручную с помощью параметра maximum_sample_files.

      Чтобы полностью сканировать JSON-файлы, укажите для этого параметра значение -1.

      Значение по умолчанию: 20480.

    • timestampformat: формат, используемый при разборе меток времени.

      Значение по умолчанию: iso.

    • union_by_name: указывает, следует ли выравнивать столбцы из разных файлов по имени, а не по позиции.

      Возможные значения:

      • true;

      • false.

      Если для этого параметра указано значение true, потребление памяти увеличивается.

      Значение по умолчанию: false.

    • map_inference_threshold: пороговое значение, при котором автоматическое определение имён столбцов и типов данных назначает JSON-объекту тип MAP вместо типа STRUCT.

      Чтобы отключить автоматическое назначение типа MAP, укажите для этого параметра значение -1.

      Значение по умолчанию: 200.

    • field_appearance_threshold: пороговое значение, определяющее, назначает ли обработчик JSON-объекту тип данных MAP или STRUCT.

      Для каждого поля обработчик JSON рассчитывает частоту появления этого поля относительно количества объектов в выборке. Если среднее значение этих показателей по всем полям объекта ниже этого порогового значения, обработчик по умолчанию присваивает этому объекту тип данных MAP.

      Значение по умолчанию: 0.1.

Postgres Pro AXE вернёт строки JSON-файлов.

Пример G.6. Чтение JSON-файлов

Содержимое file.json:

  [
    {"id": 1, "name": "Alice", "age": 30, "hired": "2020-01-15"},
    {"id": 2, "name": "Bob", "age": 25, "hired": "2021-03-22"},
    {"id": 3, "name": "Charlie", "age": 35, "hired": "2019-07-01"}
  ]
  
  SELECT * FROM read_json('file.json');
  
   id |  name   | age |   hired
  ----+---------+-----+------------
  1 | Alice   | 30  | 2020-01-15
  2 | Bob     | 25  | 2021-03-22
  3 | Charlie | 35  | 2019-07-01
  

Вы можете выбирать определённые столбцы, назначив процедуре псевдоним, например r, и используя синтаксис r['имя_столбца']:

  SELECT r['id']::INTEGER    AS id,
         r['name']::VARCHAR  AS name,
         r['age']::INTEGER   AS age,
         r['hired']::DATE    AS hired
  FROM read_json('file.json') AS r
  WHERE r['age']::INTEGER = 25;
  
   id | name | age |   hired
  ----+------+-----+------------
  2 | Bob  |  25 | 2021-03-22
  

G.4. Reading JSON Files (read_json) #

Required privileges: Superuser or the Postgres Pro AXE administrator.

For more information about access management, refer to Chapter 17.

Execute the following command on the Postgres Pro AXE server:

  SELECT * FROM read_json('path', optional_parameters);
  

Where:

  • path: The path to the JSON files that must be read.

    You can specify a value in one of the following formats:

    • a path to a single JSON file, such as 'file.json'

    • a glob pattern, such as 'data/*.json'

    • an array of paths, such as ['file1.json', 'file2.json']

  • optional_parameters: The optional parameters, specified in the parameter := value format.

    Available parameters:

    • compression: The file compression method.

      Possible values:

      • auto_detect

      • none

      • gzip

      • zstd

      Default value: auto_detect — the compression method is detected automatically using file extensions.

    • filename: Specifies whether to return the filename column with file paths. Since DuckDB v1.3.0, this column is added automatically.

      Possible values:

      • true

      • false

      Default value: false.

    • format: The JSON format.

      Possible values:

      • auto

      • unstructured

      • newline_delimited

      • array

      Default value: array.

    • hive_partitioning: Specifies whether the directory is associated with a partitioned analytical table and whether partition columns are returned.

      Possible values:

      • true

      • false

      Default value: Detected automatically based on the directory structure.

      For more information about Hive partitioning, refer to Section 15.2.

    • ignore_errors: Specifies whether to ignore parsing errors.

      Possible values:

      • true

      • false

      This parameter is applicable only if the format parameter is set to newline_delimited.

      Default value: false.

    • maximum_sample_files: The maximum number of JSON files sampled for automatic detection of column names and data types.

      You can specify the number of JSON objects sampled within each file manually using the sample_size parameter.

      Default value: 32.

    • maximum_object_size: The maximum size of a JSON object, in bytes.

      Default value: 16777216.

    • auto_detect: Specifies whether to automatically detect column names and data types.

      Possible values:

      • true

      • false

      Default value: true.

    • dateformat: The format used when parsing dates.

      Default value: iso.

    • maximum_depth: The maximum nesting depth for automatic detection of column names and data types.

      Default value: -1 — no nesting depth limit.

    • records: Specifies whether to return JSON objects as individual columns.

      Possible values:

      • auto

      • true

      • false

      If this parameter is set to false, each JSON object is returned as a STRUCT value.

      Default value: auto.

    • sample_size: The number of JSON objects sampled within each file for automatic detection of column names and data types.

      You can specify the number of sampled JSON files manually using the maximum_sample_files parameter.

      To scan JSON files entirely, set this parameter to -1.

      Default value: 20480.

    • timestampformat: The format used when parsing timestamps.

      Default value: iso.

    • union_by_name: Specifies whether columns from different files are aligned by name instead of by position.

      Possible values:

      • true

      • false

      If this parameter is set to true, memory consumption increases.

      Default value: false.

    • map_inference_threshold: The threshold at which automatic detection of column names and data types assigns the MAP type instead of the STRUCT type to a JSON object.

      To disable automatic assignment of the MAP type, set this parameter to -1.

      Default value: 200.

    • field_appearance_threshold: The threshold that determines whether the JSON reader assigns the MAP or the STRUCT data type to a JSON object.

      For each field, the JSON reader calculates how frequently the field appears relative to the number of objects in the sample. If the average of these ratios across all fields of an object is below this threshold, the reader defaults to assigning the MAP data type to this object.

      Default value: 0.1.

Postgres Pro AXE will return rows of JSON files.

Example G.6. Reading JSON Files

Contents of file.json:

  [
    {"id": 1, "name": "Alice", "age": 30, "hired": "2020-01-15"},
    {"id": 2, "name": "Bob", "age": 25, "hired": "2021-03-22"},
    {"id": 3, "name": "Charlie", "age": 35, "hired": "2019-07-01"}
  ]
  
  SELECT * FROM read_json('file.json');
  
   id |  name   | age |   hired
  ----+---------+-----+------------
  1 | Alice   | 30  | 2020-01-15
  2 | Bob     | 25  | 2021-03-22
  3 | Charlie | 35  | 2019-07-01
  

You can select specific columns by assigning an alias to a procedure, such as r, and using the r['column_name'] syntax:

  SELECT r['id']::INTEGER    AS id,
         r['name']::VARCHAR  AS name,
         r['age']::INTEGER   AS age,
         r['hired']::DATE    AS hired
  FROM read_json('file.json') AS r
  WHERE r['age']::INTEGER = 25;
  
   id | name | age |   hired
  ----+------+-----+------------
  2 | Bob  |  25 | 2021-03-22
  

FAQ