技术 · 思考 · 实践 · 成长

首页/Postgresql/正文

PostgreSQL JSONB 完全指南:操作符、查询与索引

Postgresql1 次阅读

JSONB 是 PostgreSQL 的王牌特性:JSON 存进数据库还能高效查询建索引。本文讲操作符、函数与索引,结尾附筛选小案例。

一、JSON vs JSONB

对比JSONJSONB
存储原文文本二进制分解
写入速度快稍慢(要解析)
查询速度慢(每次解析)快
可索引否✅ GIN
键顺序/重复保留去重、按键排序

选型:默认 JSONB(除非只存不查)。

二、操作符速查

CREATE TABLE products (id SERIAL PRIMARY KEY, attrs JSONB);
INSERT INTO products (attrs) VALUES
    ('{"name":"键盘","color":"black","specs":{"switch":"red","weight":800},"tags":["hot","mech"]}');

attrs->'name'             -- "键盘"(JSON 对象)
attrs->>'name'            -- 键盘(文本,最常用)
attrs#>'{specs,switch}'    -- "red"(路径取值)
attrs#>>'{specs,weight}'   -- 800(文本)
attrs->0                  -- 数组取元素(下标)
attrs @> '{"color":"black"}'        -- 包含(可走索引!)
attrs ? 'tags'                      -- 是否存在键
attrs ?| array['tags','name']        -- 任一存在
attrs ?& array['tags','name']        -- 全部存在

三、常用函数

jsonb_set(attrs, '{specs,weight}', '900')       -- 修改嵌套值
attrs || '{"warranty":12}'::jsonb                -- 合并
attrs - 'color'                                 -- 删除键
jsonb_array_elements(attrs->'tags')             -- 数组拆行
jsonb_each(attrs)                               -- 键值对拆行
jsonb_pretty(attrs)                             -- 美化输出
jsonb_typeof(attrs->'name')                     -- 值类型

四、GIN 索引(重点)

CREATE INDEX idx_products_attrs ON products USING gin (attrs);
CREATE INDEX idx_products_attrs_path ON products USING gin ((attrs->'tags'));

-- 这些查询都能走 GIN:
SELECT * FROM products WHERE attrs @> '{"color":"black"}';
SELECT * FROM products WHERE attrs ? 'tags';
SELECT * FROM products WHERE attrs @> '{"tags":["hot"]}';

jsonb_path_ops 更紧凑(只支持 @>):USING gin (attrs jsonb_path_ops)。

五、索引查询注意

  • ->> = '值' 普通等值可能走不到 GIN —— 改用 @> 或对表达式建 B-tree 索引;
  • 表达式索引:CREATE INDEX ON products ((attrs->>'name')) 后 WHERE attrs->>'name' = '键盘' 走索引;
  • 高频过滤字段建议提取成真列(生成列)。

六、小案例:商品属性筛选

-- 电商筛选:颜色黑 + 含 hot 标签 + 重量 500-1000
SELECT id, attrs->>'name' AS 名称,
       attrs#>>'{specs,weight}' AS 重量
FROM products
WHERE attrs @> '{"color":"black"}'
  AND attrs @> '{"tags":["hot"]}'
  AND (attrs#>>'{specs,weight}')::INT BETWEEN 500 AND 1000;

-- 动态更新库存属性
UPDATE products
SET attrs = jsonb_set(attrs, '{stock}', '50')
          || '{"updated":true}'::jsonb
WHERE id = 1;

-- 聚合:按标签统计(数组拆行)
SELECT tag, count(*)
FROM products, jsonb_array_elements_text(attrs->'tags') AS tag
GROUP BY tag ORDER BY count(*) DESC;

-- 生成列:高频字段提列 + 索引(PG12+)
ALTER TABLE products
    ADD COLUMN color TEXT GENERATED ALWAYS AS (attrs->>'color') STORED;
CREATE INDEX idx_products_color ON products (color);
SELECT * FROM products WHERE color = 'black';   -- 稳定走索引

筛选(@> + GIN)、更新(jsonb_set/||)、聚合(拆行)、生成列提字段 —— JSONB 生产四板斧。

七、总结

JSONB 查询快可索引(默认选它);->> 取文本、@> 查包含(走 GIN);jsonb_set 改、|| 合并;高频字段用生成列提列建索引。

顺,不妄喜;逆,不惶馁;安,不奢逸;危,不惊惧。--史记

评论交流

0 条评论 · 支持多级回复
验证码
暂无评论,来说说你的想法吧

相关文章

继续阅读