sql - 为什么不使用 GIN 索引?

标签 sql postgresql indexing jsonb

我有一个 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)

and 未使用,当我使用 ->> 运算符时:

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)))

请解释为什么?

最佳答案

来自 the documentation:

The default GIN operator class for jsonb supports queries with top-level key-exists operators ?, ?& and ?| operators and path/value-exists operator @>.

您可以创建一个 B 树索引,该索引可以与 ->> 运算符一起使用,例如

CREATE INDEX ON activities ((data->>'state'));

关于sql - 为什么不使用 GIN 索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50001690/

相关文章:

java - 使用 JDBC 在 PostgreSQL 上缓慢插入

sql-server - 复合非聚集索引和覆盖索引有什么区别

在 R 中的 For 循环中引用数组中的元素 - 初学者

sql - 更新 SQL Server XML 列中的 XML 属性

mysql - 如何按 group by 和 计算行数并将其添加到子查询中?

php - 出现 MySQL 错误 "unknown column"但该列存在

postgresql - 当我具有高度值属性时,如何将 2D OSM 多边形转换为 3D?

mysql - 正向工程错误 1054 MySQL 研讨会

postgresql - 你如何运行 ActiveRecord `find_each` 到 postgres 中的物化 View

mysql - 这个 MySQL tinyblob key 的 "length"应该是什么?