半结构化数据建模(JSON/XML)

数据建模入门数据建模

问题

如何在关系数据库中建模和查询JSON/XML等半结构化数据?

答题要点

使用JSONB类型和JSON函数:

-- PostgreSQL JSONB类型存储半结构化数据
CREATE TABLE product_catalog (
    product_id SERIAL PRIMARY KEY,
    product_name VARCHAR(200),
    category VARCHAR(100),
    -- 半结构化属性(不同产品类别有不同属性)
    attributes JSONB,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 插入不同类别产品(属性schema不同)
-- 电子产品
INSERT INTO product_catalog (product_name, category, attributes)
VALUES ('iPhone 15', '手机', '{
    "brand": "Apple",
    "color": "黑色",
    "storage": "256GB",
    "screen_size": 6.1,
    "battery_mah": 3279,
    "5g_support": true,
    "colors_available": ["黑色", "白色", "蓝色"]
}');

-- 图书
INSERT INTO product_catalog (product_name, category, attributes)
VALUES ('数据仓库工具箱', '图书', '{
    "author": "Ralph Kimball",
    "publisher": "机械工业出版社",
    "isbn": "9787111544073",
    "pages": 500,
    "language": "中文",
    "tags": ["数据仓库", "维度建模"]
}');

-- 服装
INSERT INTO product_catalog (product_name, category, attributes)
VALUES ('T恤', '服装', '{
    "material": "棉",
    "sizes": ["S", "M", "L", "XL"],
    "colors": ["红", "蓝", "白"],
    "care_instructions": "冷水手洗"
}');

-- JSON查询: 提取字段
SELECT
    product_name,
    category,
    attributes->>'brand' AS brand, -- ->> 返回text
    attributes->'screen_size' AS screen_size, -- -> 返回JSONB
    (attributes->>'battery_mah')::INT AS battery_mah -- 类型转换
FROM product_catalog
WHERE category = '手机';

-- JSON数组查询: 展开数组
SELECT
    product_name,
    jsonb_array_elements_text(attributes->'colors_available') AS color
FROM product_catalog
WHERE attributes ? 'colors_available'; -- ? 检查key存在

-- JSON条件过滤
SELECT product_name, attributes
FROM product_catalog
WHERE attributes @> '{"brand": "Apple"}'; -- @> 包含操作符
  AND (attributes->>'screen_size')::DECIMAL > 6.0;

-- JSON GIN索引(加速查询)
CREATE INDEX idx_product_attributes ON product_catalog USING GIN (attributes);

-- 聚合JSON数据
SELECT
    category,
    COUNT(*) AS product_count,
    jsonb_agg(attributes->>'brand') FILTER (WHERE attributes ? 'brand') AS brands
FROM product_catalog
GROUP BY category;

-- 更新JSON字段
UPDATE product_catalog
SET attributes = jsonb_set(
    attributes,
    '{price}', -- JSON路径
    '5999', -- 新值
    true -- 创建如果不存在
)
WHERE product_name = 'iPhone 15';

-- 删除JSON字段
UPDATE product_catalog
SET attributes = attributes - 'old_field'
WHERE product_id = 1;

-- 复杂JSON查询: 嵌套对象
CREATE TABLE user_profiles (
    user_id SERIAL PRIMARY KEY,
    user_name VARCHAR(200),
    profile JSONB
);

INSERT INTO user_profiles (user_name, profile) VALUES
('张三', '{
    "age": 30,
    "address": {
        "city": "北京",
        "district": "朝阳区",
        "street": "建国路1号"
    },
    "interests": ["数据分析", "跑步", "摄影"],
    "purchase_history": [
        {"product": "iPhone", "date": "2024-01-15", "amount": 5999},
        {"product": "MacBook", "date": "2024-03-20", "amount": 12999}
    ]
}');

-- 查询嵌套对象
SELECT
    user_name,
    profile->'address'->>'city' AS city,
    profile->'address'->>'district' AS district
FROM user_profiles;

-- 查询JSON数组元素
SELECT
    user_name,
    purchase->>'product' AS product,
    (purchase->>'amount')::DECIMAL AS amount
FROM user_profiles,
    jsonb_array_elements(profile->'purchase_history') AS purchase
WHERE (purchase->>'amount')::DECIMAL > 10000;

-- 计算总消费(JSON数组聚合)
SELECT
    user_name,
    SUM((purchase->>'amount')::DECIMAL) AS total_spent
FROM user_profiles,
    jsonb_array_elements(profile->'purchase_history') AS purchase
GROUP BY user_name;

-- JSON Schema验证(PostgreSQL 14+)
-- 定义JSON Schema
CREATE TABLE json_schemas (
    schema_name VARCHAR(100) PRIMARY KEY,
    schema JSONB
);

INSERT INTO json_schemas VALUES ('product_schema', '{
    "type": "object",
    "required": ["brand", "price"],
    "properties": {
        "brand": {"type": "string"},
        "price": {"type": "number", "minimum": 0}
    }
}');

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题