json类型以文本方式存储json对象,把输入的数据原封不动的存放到数据库中,会保留多余的空格,保留重复的Key,保留Key的顺序。
jsonb类型转换文本格式json对象为二进制格式,不保留多余的空格,不保留重复的Key,不保留Key的顺序,同时支持索引。
jsonb类型除了支持json类型的操作符外,还支持以下的操作符。
继续使用之前的student表添加jsonb数据类型列
alter table student add (stu_info_b jsonb);
update student set stu_info_b = stu_info;
可以看到jsonb类型的数据结构已经发生了变动。
@>和<@操作符
test=# select stu_info_b @> '{"name": "lisi"}' from student;
?column?
----------
t
f
f
f
(4 行记录)
test=# select stu_info_b @> '{"rank": 12}' from student;
?column?
----------
f
f
f
f
(4 行记录)
test=# select stu_info_b @> '{"information":{"branch": "Computer"}}' from student;
?column?
----------
t
t
f
f
(4 行记录)
test=# select stu_info_b from student where stu_info_b @> '{"information":{"branch": "Computer"}}';
stu_info_b
--------------------------------------------------------------------------------------------------------
{"name": "lisi", "information": {"rank": 12, "branch": "Computer", "mobile_number": "13700000001"}}
{"name": "zhangsan", "information": {"rank": 1, "branch": "Computer", "mobile_number": "13700000002"}}
(2 行记录)
从结果可以看出 @> 操作符只能判断jsonb对象顶层是否包含右侧的数据,无法单独判断嵌套结构中的键值。
<@ 操作符与之相反,用于判断左边的json对象是否包含与右边。
?操作符、?|操作符和?&操作符
test=# select stu_info_b ? 'rank' from student;
?column?
----------
f
f
f
f
(4 行记录)
test=# select stu_info_b ? 'name' from student;
?column?
----------
t
t
t
t
(4 行记录)
test=# select stu_info_b -> 'information' ? 'rank' from student;
?column?
----------
t
t
t
t
(4 行记录)
test=# select stu_info_b ?| array['name','id'] from student;
?column?
----------
t
t
t
t
(4 行记录)
test=# select stu_info_b ?| array['rank','id'] from student;
?column?
----------
f
f
f
f
(4 行记录)
test=# select stu_info_b ?& array['name','id'] from student;
?column?
----------
f
f
f
f
(4 行记录)
test=# select stu_info_b ?& array['name'] from student;
?column?
----------
t
t
t
t
(4 行记录)
这3个符号都只能判断json对象的顶层的情况,对于嵌套对象需要借助 -> 操作符来进行判断。