2.2、jsonb应用

2.2.1、创建jsonb类型字段表

  1. postgres=# create table t_jsonb(id int,f_jsonb jsonb);
  2. NOTICE: Replica identity is needed for shard table, please add to this table through "alter table" command.
  3. CREATE TABLE
  4. postgres=#

2.2.2、插入数据

  1. postgres=# insert into t_jsonb values(1,'{"col1":1,"col2":"tbase"}');
  2. INSERT 0 1
  3. postgres=# insert into t_jsonb values(2,'{"col1":1,"col2":"tbase","col3":"pgxz"}');
  4. INSERT 0 1
  5. postgres=# select * from t_jsonb;
  6. id | f_jsonb
  7. ----+----------------------------------------------
  8. 1 | {"col1": 1, "col2": "tbase"}
  9. 2 | {"col1": 1, "col2": "tbase", "col3": "pgxz"}
  10. (2 rows)

—jsonb插入时会移除重复的键,如下所示

  1. postgres=# insert into t_jsonb values(3,'{"col1":1,"col2":"tbase","col2":"pgxz"}');
  2. INSERT 0 1
  3. postgres=# select * from t_jsonb;
  4. id | f_jsonb
  5. ----+----------------------------------------------
  6. 1 | {"col1": 1, "col2": "tbase"}
  7. 3 | {"col1": 1, "col2": "pgxz"}
  8. 2 | {"col1": 1, "col2": "tbase", "col3": "pgxz"}
  9. (3 rows)

2.2.3、更新数据

—增加元素

  1. postgres=# update t_jsonb set f_jsonb = f_jsonb || '{"col3":"pgxz"}'::jsonb where id=1;
  2. UPDATE 1

—更新原来的元素

  1. postgres=# update t_jsonb set f_jsonb = f_jsonb || '{"col2":"tbase"}'::jsonb where id=3;
  2. UPDATE 1
  3. postgres=# select * from t_jsonb;
  4. id | f_jsonb
  5. ----+----------------------------------------------
  6. 2 | {"col1": 1, "col2": "tbase", "col3": "pgxz"}
  7. 1 | {"col1": 1, "col2": "tbase", "col3": "pgxz"}
  8. 3 | {"col1": 1, "col2": "tbase"}
  9. (3 rows)

—删除某个键

  1. postgres=# update t_jsonb set f_jsonb = f_jsonb - 'col3';
  2. UPDATE 3
  3. postgres=# select * from t_jsonb;
  4. id | f_jsonb
  5. ----+------------------------------
  6. 2 | {"col1": 1, "col2": "tbase"}
  7. 1 | {"col1": 1, "col2": "tbase"}
  8. 3 | {"col1": 1, "col2": "tbase"}
  9. (3 rows)

2.2.4、jsonb_set()函数更新数据

  1. jsonb_set(target jsonb, path text[], new_value jsonb, [create_missing boolean])

说明:target指要更新的数据源,path指路径,new_value指更新后的键值,create_missing值为true表示如果键不存在则添加,create_missing值为false表示如果键不存在则不添加。

  1. postgres=# update t_jsonb set f_jsonb = jsonb_set( f_jsonb , '{col}' , '"pgxz"' , true ) where id=1;
  2. UPDATE 1
  3. postgres=# update t_jsonb set f_jsonb = jsonb_set( f_jsonb , '{col}' , '"pgxz"' , false ) where id=2;
  4. UPDATE 1
  5. postgres=# update t_jsonb set f_jsonb = jsonb_set( f_jsonb , '{col2}' , '"pgxz"' , false ) where id=3;
  6. UPDATE 1
  7. postgres=# select * from t_jsonb;
  8. id | f_jsonb
  9. ----+---------------------------------------------
  10. 1 | {"col": "pgxz", "col1": 1, "col2": "tbase"}
  11. 2 | {"col1": 1, "col2": "tbase"}
  12. 3 | {"col1": 1, "col2": "pgxz"}
  13. (3 rows)