【发布时间】:2021-02-10 17:02:14
【问题描述】:
考虑如下定义的表:
CREATE TABLE test (
id int4 NOT NULL,
tag_counts _jsonb NOT NULL DEFAULT ARRAY[]::jsonb[]
);
INSERT INTO test(id, tag_counts) values(1,array['{"type":1, "count":4}','{"type":2, "count":10}' ]::jsonb[])
如何在 json 键 type 上创建索引以及如何对其进行查询?
编辑:以前,json键上没有索引,选择查询使用unnest操作,如下所示:
select * from (SELECT unnest(tag_counts) as tc
FROM public.test) as t
where tc->'type' = '2';
问题是,如果表的行数很大,上面的查询不仅会包括全表扫描,还会对每个jsonb数组进行过滤。
【问题讨论】:
-
jsonb[]几乎没有意义。为什么不在jsonb列中存储正确的 JSON 数组?例如'[{"type":1, "count":4}','{"type":2, "count":10}]' -
遗留问题。如果不进行重大重构,就无法真正改变它。
-
那么它是如何在遗留系统中被索引的呢?您想加快什么查询?
-
更新了问题以包括它目前是如何完成的
标签: sql postgresql postgresql-12