在 Postgres 中理解 JSON 数据

NoSQL 入门

Jake Roach

Data Engineer

Postgres 中的 JSON 与 JSONB

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

JSON

  • 以 JSON 格式存储数据
  • 键值对、数组、嵌套对象

$$

JSONB

  • 以二进制格式存储数据
  • 类似 MongoDB 的 BSON
  • 存储与读取更高效
  • 支持额外索引
NoSQL 入门

为何在 Postgres 使用半结构化数据?

包含 JSON 列的 Postgres 表。

NoSQL 入门

用 Postgres 查询 JSON 数据

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

$$

  • row_to_json, json_to_record
  • ->, ->>, #>, #>> 运算符
  • json_extract_path, json_extract_path_text

您还将能够:

  • 向 Postgres 表插入 JSON 记录
  • 表格转 JSON、JSON 转表格
  • 从 JSON 对象提取单个记录
NoSQL 入门

使用 sqlalchemy 与 pandas 执行查询

import sqlalchemy
import pandas as pd
# Create a connection
db_engine = sqlalchemy.create_engine(
    "postgresql+psycopg2://<user>:<password>@<host>:5432/<database>"
)
# Write a query
query = "SELECT * FROM table_name;"
# Execute the query, show results
results = pd.read_sql(query, db_engine)
NoSQL 入门

Let's practice!

NoSQL 入门

Preparing Video For Download...