使用一组搜索词在 JSONB 列 (PostgreSQL) 中搜索时未使用 Gin 索引

Gin Index not being used when searching in JSONB column (PostgreSQL) with an array of search terms

我有一个名为 myContent 的 JSONB 列,每行 JSON 中的一个对象如下所示:

  "metadata": {
    "key": "key",
    "teamBased": false,
  }

我想 select 所有 teamBased 的行都为 false。 这是我的查询的样子:

set enable_seqscan=false;
EXPLAIN ANALYZE
SELECT *
FROM table n
WHERE n.key = 'key'
AND myContent @> ALL(array[:searchTerms]::jsonb[]));

我从我的 Java 应用程序将 searchTerms 作为数组发送,在本例中,该数组如下所示:

 ['{"metadata":{"teamBased":false}}']

我创建了一个如下所示的 GIN 索引:

  create index "myIndex"
    on myTable using gin (myContent);

当我查看 explain analyze query 的输出时,我发现它没有使用我的索引。但是,如果我将查询更改为此


set enable_seqscan=false;
EXPLAIN ANALYZE
SELECT *
FROM table n
WHERE n.key = 'key'
AND myContent @> '{"metadata":{"teamBased":false}}';

它确实使用了它,所以我假设它与我在原始查询中的搜索词数组有问题。但是,我确实需要这样的查询,因为当我需要多个搜索词时,其他情况也会使用此查询。

这可能是什么问题?另外,如何修改我的 GIN 索引,使其不设置为整个 JSON,而是设置在其中一个对象中,例如 metadata?

谢谢!

GIN 索引不支持 @> ALL,仅支持 @>.

The documentation 说:

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