Advanced Postgres JSON query techniques

Introduction to NoSQL

Jake Roach

Data Engineer

Querying nested JSON data

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

$$

To make querying nested data easier:

  • #> and #>> operators
  • json_extract_path and json_extract_path_text functions
Introduction to NoSQL

#> and #>> operators

Two tables, the first showing document data, and the second showing several fields extracted from this document data using the hash arrow and hash double arrow operators.

#> operator

  • Called on column, takes a string array
  • Returns null if path does not exist
  • #>> returns field as text

$$

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 to NoSQL

json_extract_path and json_extract_path_text

json_extract_path

  • Provide column and arbitrary list of fields
  • Returns null if path does not exist
  • 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;

Two tables, the first showing document data, and the second showing several fields extracted from this document data using the json_extract_path and json_extract_path_text functions.

Introduction to NoSQL

Review

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 to NoSQL

Let's practice!

Introduction to NoSQL

Preparing Video For Download...