PostGreSql支持json类型的字段和jsonb类型的字段
json和jsonb的区别
一、json类型
1.添加json类型的字段
alter table t_message add params_json json;
2.创建索引
方法一:
create index idx_params_id on t_message using btree (json_extract_path_text(params_json, 'id'));
方法二:
create index idx_params_name on t_message using btree ((params_josn->>'name'));
3.执行
方法一走索引的查询
select * from test where json_extract_path_text( params_json,'id')='123';
方法二走索引的查询
select * from test where params_json->>'name'='123';
二、jsonb类型
josnb字段创建 GIN 索引, GIN 索引有两种模式, 默认模式支持 @>, ?, ?& 和 ?| 的索引查询
两者的区别是:
例如,一个项{“foo”:{"bar":"baz"}},jsonb_ops会分别为“foo”,"bar","baz"创建索引项,共创建了三个。jsonb_path_ops则是把“foo”,"bar","baz"组合成一个hash值作为索引项。因此,通常jsonb_path_ops的索引较小。
我们这里使用默认模式
1.添加jsonb类型
alter table t_message add params_jsonb jsonb;
2.添加jsonb索引
使用默认的jsonb_ops操作符创建索引。
create index idx_gin_params_jsonb on t_message using gin (params_jsonb);
使用jsonb_path_ops操作符创建索引。
create index idx_gin_params_jsonb on t_message using gin(params_jsonb jsonb_path_ops);
3.执行
不走索引:
select * from t_message where params_jsonb->>'loanId' ='123';
走索引:
select * from t_message where params_jsonb @> '{"loanId": 123}';
走索引:
select * from t_message where params_jsonb->'loanId' ?'123';
结果:没走
? 操作没走索引, 但 ? 操作支持索引检索,创建以下索引.
create index idx_gin_params_jsonb_loaId on t_message using gin((params_jsonb -> 'loanId'));
再次执行则走索引.
json and jsonb Operators
Operator |
Right Operand Type |
Description |
Example |
Example Result |
-> |
int |
Get JSON array element (indexed from zero) |
'[{"a":"foo"},{"b":"bar"},{"c":"baz"}]'::json->2 |
{"c":"baz"} |
-> |
text |
Get JSON object field by key |
'{"a": {"b":"foo"}}'::json->'a' |
{"b":"foo"} |
->> |
int |
Get JSON array element as text |
'[1,2,3]'::json->>2 |
3 |
->> |
text |
Get JSON object field as text |
'{"a":1,"b":2}'::json->>'b' |
2 |
#> |
text[] |
Get JSON object at specified path |
'{"a": {"b":{"c": "foo"}}}'::json#>'{a,b}' |
{"c": "foo"} |
#>> |
text[] |
Get JSON object at specified path as text |
'{"a":[1,2,3],"b":[4,5,6]}'::json#>>'{a,2}' |
3 |
Additional jsonb Operators
Operator |
Right Operand Type |
Description |
Example |
= |
jsonb |
Are the two JSON values equal? |
'[1,2,3]'::jsonb = '[1,2,3]'::jsonb |
@> |
jsonb |
Does the left JSON value contain within it the right value? |
'{"a":1, "b":2}'::jsonb @> '{"b":2}'::jsonb |
<@ |
jsonb |
Is the left JSON value contained within the right value? |
'{"b":2}'::jsonb <@ '{"a":1, "b":2}'::jsonb |
? |
text |
Does the key/element string exist within the JSON value? |
'{"a":1, "b":2}'::jsonb ? 'b' |
?| |
text[] |
Do any of these key/element strings exist? |
'{"a":1, "b":2, "c":3}'::jsonb ?| array['b', 'c'] |
?& |
text[] |
Do all of these key/element strings exist? |
'["a", "b"]'::jsonb ?& array['a', 'b'] |