[英]Using Postgres 9.5 GIN indexes and JSONB
I'm trying to create a Postgres GIN index to speed up the following query: 我正在尝试创建一个Postgres GIN索引来加快以下查询的速度:
CREATE TABLE foo (
id serial primary key,
a jsonb not null
);
insert into foo(a) values
('[{"b": "aaa"}, {"b": "ddd"}]'::jsonb),
('[{"b": "aaa"}, {"b": "aaa"}]'::jsonb),
('[{"b": "aaa"}]'::jsonb),
('[{"b": "aaa"}]'::jsonb),
('[{"b": "aaa"}]'::jsonb),
('[{"b": "bbb"}]'::jsonb),
('[{"b": "bbb"}]'::jsonb),
('[{"b": "bbb"}]'::jsonb),
('[{"b": "ccc"}]'::jsonb),
('[]'::jsonb);
select distinct id from (
select id, jsonb_array_elements(a)->>'b' as b from foo
) t where t.b = 'aaa'
Is such a thing possible in Postgres? 在Postgres中有这种可能吗? I am open to other alternatives as well. 我也欢迎其他选择。 Unfortunately, I can't normalize the table, so I'll need to work with the table structure that I already have. 不幸的是,我无法规范化表,所以我需要使用已经拥有的表结构。
Yes, you can apply a GIN index here but it may not be particularly useful: 是的,您可以在此处应用GIN索引,但它可能不是特别有用:
CREATE INDEX find_fast_jsonb_value
ON foo USING GIN (a jsonb_path_ops);
Now you still have to search through the arrays for matching key/value pairs. 现在,您仍然必须在数组中搜索匹配的键/值对。 Your query then becomes: 您的查询将变为:
SELECT DISTINCT id
FROM foo, jsonb_array_elements(a) AS t(b) -- Implicit LATERAL join
WHERE b @> '{"b": "aaa"}'; -- Comparing json key/values here
This also places the set-returning-function jsonb_array_elements()
in the FROM
clause, where it belongs. 这还将set-returning-functions jsonb_array_elements()
放在它所属的FROM
子句中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.