Techniques avancées de requêtes JSON dans Postgres

Introduction à NoSQL

Jake Roach

Data Engineer

Interroger des données JSON imbriquées

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

$$

Pour faciliter les requêtes sur des données imbriquées :

  • Opérateurs #> et #>>
  • Fonctions json_extract_path et json_extract_path_text
Introduction à NoSQL

Opérateurs #> et #>>

Deux tableaux : le premier affiche des documents, le second des champs extraits de ces documents avec les opérateurs dièse-flèche simple et dièse-double flèche.

Opérateur #>

  • S'applique à une colonne, prend un tableau de chaînes
  • Retourne null si le chemin n'existe pas
  • #>> retourne le champ en texte

$$

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;
Introduction à NoSQL

json_extract_path et json_extract_path_text

json_extract_path

  • Fournir la colonne et une liste arbitraire de champs
  • Retourne null si le chemin n'existe pas
  • 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;

Deux tableaux : le premier affiche des documents, le second des champs extraits avec les fonctions json_extract_path et json_extract_path_text.

Introduction à NoSQL

Révision

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>;
Introduction à NoSQL

Passons à la pratique !

Introduction à NoSQL

Preparing Video For Download...