postgres之jsonb属性的简单操作

版权声明:转载请注明出处 https://blog.csdn.net/wang_8101/article/details/81450574

jsonb的一些简单操作(增删改查)

  1. 更新操作(attributes属性为jsonb类型)
    方法定义:
    jsonb_set(target jsonb, path text[], new_value jsonb[, create_missing boolean])
    参数:
    target:目标(jsonb类型的属性)
    path :不是很懂,网上搜索了一些资料,都没有解释这个该如何写,不是很懂官网给的例子0是什么意思
    new_value:新值
    选填参数:create_missing:jsonb字段不存在f1属性时创建,默认为true
    官方文档给出的示例:
jsonb_set('[{"f1":1,"f2":null},2,null,3]', '{0,f1}','[2,3,4]', false)
结果:[{"f1":[2,3,4],"f2":null},2,null,3]

jsonb_set('[{"f1":1,"f2":null},2]', '{0,f3}','[2,3,4]')
结果:[{"f1": 1, "f2": null, "f3": [2, 3, 4]}, 2]
-- attributes为jsonb类型字段
原值:{"a":"1"}
update user_test set attributes = jsonb_set(attributes,'{a}','"0"'::jsonb, false) where id = '8888';
执行后:{"a":"0"}

查询

select value from json_each('{"a":"foo", "b":"bar"}') where key = 'a'
select * from json_object_keys('{"a":"foo", "b":"bar"}')
select * from json_object_keys('{"f1":"abc","f2":{"f3":"a", "f4":"b"}}')
select  * from json_object_keys(from ci_type.attributes);--错误
select * from to_jsonb('"a":1,"b":2') 
 select '{"a":1,"b":2}'::json->>'b' --获取jsonb中对应键的值(文本)

 --select * from json_each( to_jsonb(select distinct attributes from ci_type ) )
 --select to_jsonb(select distinct attributes from ci_type ) 

--扩展字段提取相应属性的值
  select  attributes :: json->>'instanceType' from ci_type 
-- 属性值转为jsonb
select to_jsonb('id:'||id::text) from ci

--jsonb添加属性,删除属性
select '{"a":"foo", "b":"bar"}'::jsonb || '{"c":"fc", "d":"bdd"}'::jsonb--添加
select '{"a":"foo", "b":"bar"}'::jsonb -'c'-'d'-'a'||'{"a":2}'--删除
select '{"a": "b","c":3}'::jsonb - 'a'

猜你喜欢

转载自blog.csdn.net/wang_8101/article/details/81450574