Postgresql 不对“?”使用 GIN 索引JSON 运算符

Postgresql doesn't use GIN index for "?" JSON operator

由于某些原因索引没有用于“?”运算符。

让我们以这个例子为例 https://schinckel.net/2014/05/25/querying-json-in-postgres/ :

  CREATE TABLE json_test (
  id serial primary key,
  data jsonb
  );

  INSERT INTO json_test (data) VALUES 
  ('{}'),
  ('{"a": 1}'),
  ('{"a": 2, "b": ["c", "d"]}'),
  ('{"a": 1, "b": {"c": "d", "e": true}}'),
  ('{"b": 2}');

并创建索引。

create index json_test_index on public.json_test using gin (data jsonb_path_ops) tablespace pg_default;

然后看看下面查询的计划:

SELECT * FROM json_test WHERE data ? 'a';

将进行序列扫描,而我希望进行索引扫描。有人可以告诉我这里出了什么问题吗?

来自 the docs:"The non-default GIN operator class jsonb_path_ops supports indexing the @> operator only." 它不支持 ? 运算符。

因此请改用 jsonb 的默认运算符(称为 "jsonb_ops",如果您想明确拼写的话)。

但是如果你的 table 只有 5 行,它可能不会使用索引,除非你通过 set enable_seqscan = off.

强制它