JSON-gegevens in Postgres begrijpen

Introductie tot NoSQL

Jake Roach

Data Engineer

JSON en JSONB in Postgres

{
    'guardian': 'mother',
    'status': 'A',
    'educations': [4, 4],
    'jobs': {
        'P1': 'teacher',
        'P2': 'at_home'
    }
}
CREATE TABLE students
    <column-name> JSON,
    <column-bame> JSONB
;

JSON

  • Slaat data op in JSON-indeling
  • Sleutel-waardeparen, arrays, geneste objecten

$$

JSONB

  • Data wordt binair opgeslagen
  • Vergelijkbaar met BSON in MongoDB
  • Efficiëntere opslag en opvraging
  • Ondersteunt extra indexering
Introductie tot NoSQL

Waarom semi-gestructureerde data in Postgres?

Een Postgres-tabel met een kolom van het type JSON.

Introductie tot NoSQL

JSON-data query’en met Postgres

SELECT
    address,
    famsize,
    ...
FROM students
[WHERE | GROUP BY | ORDER BY];

$$

  • row_to_json, json_to_record
  • ->, ->>, #>, #>>-operatoren
  • json_extract_path, json_extract_path_text

We kunnen ook:

  • JSON-records in een Postgres-tabel invoegen
  • Tabel → JSON, JSON → tabel
  • Individuele waarden uit JSON-objecten halen
Introductie tot NoSQL

Queries uitvoeren met sqlalchemy en pandas

import sqlalchemy
import pandas as pd
# Maak een connectie
db_engine = sqlalchemy.create_engine(
    "postgresql+psycopg2://<user>:<password>@<host>:5432/<database>"
)
# Schrijf een query
query = "SELECT * FROM table_name;"
# Voer de query uit en toon resultaten
results = pd.read_sql(query, db_engine)
Introductie tot NoSQL

Laten we oefenen!

Introductie tot NoSQL

Preparing Video For Download...