Tecniche avanzate di query JSON in Postgres

Introduzione ai database NoSQL

Jake Roach

Data Engineer

Query su dati JSON annidati

SELECT
    parent_meta -> 'jobs' ->> 'P1' AS jobs_P1,
    parent_meta -> 'jobs' ->> 'P2' AS jobs_P2
FROM student;

$$

Per semplificare le query su dati annidati:

  • operatori #> e #>>
  • funzioni json_extract_path e json_extract_path_text
Introduzione ai database NoSQL

Operatori #> e #>>

Due tabelle: la prima mostra dati documento, la seconda vari campi estratti da questi dati usando gli operatori cancelletto-freccia e cancelletto-doppia-freccia.

Operatore #>

  • Si usa sulla colonna, accetta un array di stringhe
  • Restituisce null se il percorso non esiste
  • #>> restituisce il campo come testo

$$

SELECT
    parent_meta #> '{jobs}' AS jobs,
    parent_meta #> '{jobs, P1}' AS jobs_P1,
    parent_meta #> '{jobs, income}' AS income,
    parent_meta #>> '{jobs, P2}' AS jobs_P2
FROM student;
Introduzione ai database NoSQL

json_extract_path e json_extract_path_text

json_extract_path

  • Fornisci la colonna e un elenco arbitrario di campi
  • Restituisce null se il percorso non esiste
  • json_extract_path_text

$$

SELECT
  json_extract_path(parent_meta, 'jobs') AS jobs,
  json_extract_path(parent_meta, 'jobs', 'P1') AS jobs_P1,
  json_extract_path(parent_meta, 'jobs', 'income') AS income,
  json_extract_path_text(parent_meta, 'jobs', 'P2') AS jobs_P2,
FROM student;

Due tabelle: la prima mostra dati documento, la seconda vari campi estratti da questi dati usando le funzioni json_extract_path e json_extract_path_text.

Introduzione ai database NoSQL

Riepilogo

SELECT
    <column-name> #> '{<field-name>}' AS <alias>,
    <column-name> #> '{<field-name>, <field-name>}' AS <alias>,
    <column-name> #>> '{<field-name>, <field-name>}' AS <alias>
FROM <table-name>;
SELECT
  json_extract_path(<column-name>, '<field-name>') AS <alias>,
  json_extract_path(<column-name>, '<field-name>', '<field-name>') AS <alias>,
  json_extract_path_text(<column-name>, '<field-name>', '<field-name>') AS <alias>
FROM <table-name>;
Introduzione ai database NoSQL

Esercitiamoci!

Introduzione ai database NoSQL

Preparing Video For Download...