Postgresql 将平面jsonb迁移到hstore
我运行Postgres9.4,希望将数据库表中的列迁移到hstore,以便能够进行性能比较 我的当前列是jsonb中的键值对,没有嵌套结构 如何解决此问题的任何提示?示例数据:Postgresql 将平面jsonb迁移到hstore,postgresql,hstore,jsonb,Postgresql,Hstore,Jsonb,我运行Postgres9.4,希望将数据库表中的列迁移到hstore,以便能够进行性能比较 我的当前列是jsonb中的键值对,没有嵌套结构 如何解决此问题的任何提示?示例数据: create table jsons (id int, val jsonb); insert into jsons values (1, '{"age":22}'), (2, '{"height":182}'), (3, '{"age":30, "height":177}'); 将json对象拆分为键,值对:
create table jsons (id int, val jsonb);
insert into jsons values
(1, '{"age":22}'),
(2, '{"height":182}'),
(3, '{"age":30, "height":177}');
将json对象拆分为键
,值
对:
select id, (jsonb_each_text(val)).key, (jsonb_each_text(val)).value
from jsons
id | key | value
----+--------+-------
1 | age | 22
2 | height | 182
3 | age | 30
3 | height | 177
(4 rows)
聚合对并将其转换为hstore:
select id, hstore(array_agg(key), array_agg(value))
from (
select id, (jsonb_each_text(val)).key, (jsonb_each_text(val)).value
from jsons
) sub
group by 1
order by 1
id | hstore
----+------------------------------
1 | "age"=>"22"
2 | "height"=>"182"
3 | "age"=>"30", "height"=>"177"
(3 rows)
使用横向连接可以以更优雅的方式实现这一点:
select id, hstore(array_agg(key), array_agg(value))
from jsons
cross join jsonb_each_text(val)
group by 1
order by 1;
最后一段代码对我和你都有帮助。还感谢其他人提供的分步指导。第一步只是为了说明第二步(为了更好地理解查询)。不客气。