我有一个jsonb字段,其数据如下:
{"state": "initialize_done_state", ... }
此字段的GIN索引:
CREATE INDEX index_activities_on_data ON activities USING gin (data)
并执行查询:
select count(*)
from activities a
where a.created_at >= (date_trunc('month', current_date)::timestamp AT TIME ZONE 'MSK') and
--a.data ->> 'state' = 'issued_success_state';
a.data @> '{ "state": "issued_success_state" }';
当我使用@> WHERE子句中的运算符,使用了gin索引:
Aggregate (cost=406.91..406.92 rows=1 width=8)
-> Bitmap Heap Scan on activities a (cost=32.75..406.67 rows=95 width=0)
Recheck Cond: (data @> '{"state": "issued_success_state"}'::jsonb)
Filter: (created_at >= timezone('MSK'::text, (date_trunc('month'::text, (('now'::cstring)::date)::timestamp with time zone))::timestamp without time zone))
-> Bitmap Index Scan on index_activities_on_data (cost=0.00..32.73 rows=364 width=0)
Index Cond: (data @> '{"state": "issued_success_state"}'::jsonb)
并且在我使用时不使用 - >>操作者:
Aggregate (cost=59093.42..59093.43 rows=1 width=8)
-> Seq Scan on activities a (cost=0.00..59092.23 rows=477 width=0)
Filter: (((data ->> 'state'::text) = 'issued_success_state'::text) AND (created_at >= timezone('MSK'::text, (date_trunc('month'::text, (('now'::cstring)::date)::timestamp with time zone))::timestamp without time zone)))
请解释原因?
答案 0 :(得分:2)
jsonb的默认GIN运算符类支持使用顶级键存在运算符的查询?,?&和?|运算符和路径/值存在运算符@>。
您可以创建可与->>
运算符一起使用的B树索引,例如
CREATE INDEX ON activities ((data->>'state'));