【问题标题】:Search and update a JSON array element in Postgres在 Postgres 中搜索和更新 JSON 数组元素
【发布时间】:2018-09-14 03:56:38
【问题描述】:

我有一个 Jsonb 列,它存储如下元素数组:

[ 
  {"id": "11", "name": "John", "age":"25", ..........}, 
  {"id": "22", "name": "Mike", "age":"35", ..........},
  {"id": "33", "name": "Tom",  "age":"45", ..........},
  .....
]

我想用一个全新的对象替换第二个对象(id=22)。我不想一个一个地更新每个属性,因为有很多属性,它们的值都可能已经改变。我只想识别第二个元素并替换整个对象。

我知道有一个 jsonb_set()。但是,要更新第二个元素,我需要知道它的数组 index=1 以便我可以执行以下操作:

jsonb_set(data, '{1}', '{"id": "22", "name": "Don", "age":"55"}',true) 

但我找不到任何方法来搜索和获取该索引。有人可以帮我吗?

【问题讨论】:

标签: postgresql postgresql-9.5


【解决方案1】:

我能想到的一种方法是结合row_numberjson_array_elements

-- test data
create table test (id integer, data jsonb);
insert into test values (1, '[{"id": "22", "name": "Don", "age":"55"}, {"id": "23", "name": "Don2", "age":"55"},{"id": "24", "name": "Don3", "age":"55"}]');
insert into test values (2, '[{"id": "32", "name": "Don", "age":"55"}, {"id": "33", "name": "Don2", "age":"55"},{"id": "34", "name": "Don3", "age":"55"}]');

select subrow, id, row_number() over (partition by id) 
from (
    select json_array_elements(data) as subrow, id 
    from test
) as t;
                  subrow                  | id | row_number
------------------------------------------+----+------------
 {"id": "22", "name": "Don", "age":"55"}  |  1 |          1
 {"id": "23", "name": "Don2", "age":"55"} |  1 |          2
 {"id": "24", "name": "Don3", "age":"55"} |  1 |          3
 {"id": "32", "name": "Don", "age":"55"}  |  2 |          1
 {"id": "33", "name": "Don2", "age":"55"} |  2 |          2
 {"id": "34", "name": "Don3", "age":"55"} |  2 |          3

-- apparently you can filter what you want from here
select subrow, id, row_number() over (partition by id) 
from (
    select json_array_elements(data) as subrow, id 
    from test
) as t
where subrow->>'id' = '23';

此外,请考虑您的架构设计。以这种方式存储数据可能不是最好的主意。

【讨论】:

  • 感谢您的快速回复@blurrcat。我正在尝试通过一个查询来完成更新。使用您的解决方案,如何将 row_number 传递给 jsonb_set()?
  • 我从字面上回答了您关于“获取该索引”的问题。如果可能的话,在一个查询中完成它会很尴尬。此外,请考虑有多个子行匹配该 id 的情况。如果您有权更改架构,我认为最好将这些子行放在单独的表中。
  • 好的,@blurrcat。谢谢你。您能否详细说明您对架构设计的建议?有什么更好的方法?
  • @user3487866 将数组项放在单独的表中怎么样?
猜你喜欢
  • 1970-01-01
  • 2021-04-17
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多