PostgreSQL中Json类型使用

一、创建测试表

CREATE TABLE job( jobid SERIAL primary key , jobdesc json)

二、选择符

->(返回对象类型)->>(返回字符型)#>>(选择数组类型)

三、插入选择更新删除操作记录

1.插入记录
insert into job(jobdesc) values('{
        "jobname":"linux_os_vmstat",
        "schedule":{
            "type":{"interval":"5m" },
            "start":"now","end":"None"
        },"values":{
            "event":["cpu_r","cpu_w"], "data":["cpu_r"], "threshold":[1,1]
        },"objects":{
            "wintest1":"cpu"
        }
}');

insert into job(jobdesc) values('{
        "jobname":"[Oracle](http://www.linuxidc.com/topicnews.aspx?tid=12)_tbs_space",
        "schedule":{
            "type":{"interval":"1d"},
            "start":"now","end":"None"},
            "values":{"event":["used"],"data":["used"],"threshold":["90%"]},
            "objects":{"wintest1":"oradb1"}
}');
2.选择记录
select jobdesc->>'jobname' as jobname from job where jobdesc->'objects'->>'wintest1' like 'oradb1';
result:
jobname
oracle_tbs_space
(1 行记录)
select jobdesc->'objects' as objects from job where jobdesc->>'jobname' = 'linux_os_vmstat';  
result:
objects
{ “wintest1″:”cpu”}
(1 行记录)
3.数组元素选择
select jobdesc->'values'#>>'{event,0}' as value1 from job where jobdesc->>'jobname' = 'linux_os_vmstat';
result:
value1
cpu_r
(1 行记录)
select jobdesc->'values'#>>'{event,1}' as value2 from job where jobdesc->>'jobname' = 'linux_os_vmstat';
result:
value2
cpu_w
(1 行记录)
4.更新记录
update job set jobdesc = '{
        "jobname":"linux_os_vmstat",
        "schedule":{
            "type":{"interval":"5m"},
            "start":"now",
            "end":"None"
        },"values":{
            "event":["cpu_r","cpu_w"],
            "data":["cpu_r"],
            "threshold":[1,2]
        },
        "objects":{"wintest1":"cpu"}
}' where jobdesc->>'jobname' = 'linux_os_vmstat';
UPDATE 1#
select jobdesc->'values'#>>'{threshold,1}' as threshold2 from jobwhere jobdesc->>'jobname' = 'linux_os_vmstat';
result:
threshold2
2
(1 行记录)
注:更新json类型字段时必须整个字段都更新,无法采用指定内部特定值方法更新。
5.删除记录
select * from job;
result:

|jobid | jobdesc|
|——————————————|
|3 | {“jobname”:”oracle_tbs_space”,”schedule”:{+”type”:{“interval”:+”1d”},”start”:”now”,”end”:”None”},”values”:{“event”:[“used”],”data”:[“used”],”threshold”:[“90%”]},”objects”:{“wintest1″:”oradb1”}}|
|4 | {“jobname”:”linux_os_vmstat”,”schedule”:{“type”:{“interval”:”5m”},”start”:”now”,”end”:”None”},”values”:{“event”:[“cpu_r”,”cpu_w”],”data”:[“cpu_r”],”threshold”:[1,1]}”objects”:{“wintest1″:”cpu”}}|

(2 行记录)
delete from job where jobdesc->>'jobname' = 'linux_os_vmstat';
DELETE 1
select * from job;
result:

|jobid | jobdesc|
|——————————————|
|3 | {“jobname”:”oracle_tbs_space”,”schedule”:{+”type”:{“interval”:+”1d”},”start”:”now”,”end”:”None”},”values”:{“event”:[“used”],”data”:[“used”],”threshold”:[“90%”]},”objects”:{“wintest1″:”oradb1”}}|

(1 行记录)
文章转载自:http://www.linuxidc.com/Linux/2013-12/94354.htm
    原文作者:暗香抚动
    原文地址: https://www.jianshu.com/p/ec18c113ab59
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞