是否可以使用 json 包含列创建 PostgreSQL 索引?

Is it possible to create a PostgreSQL index with json Include Columns?

我正在使用 PostgreSQL11.8

CREATE INDEX ix_products_product_sku_with_json_columns
ON products USING btree((product_sku))
INCLUDE ((data->>'variantCode'));

ERROR: expressions are not supported in included columns
SQL state: 0A000

Documentation 说:

Expressions are not supported as included columns since they cannot be used in index-only scans.

我想 data->>'variantCode' 是一个表达式,故事就这样结束了吗?
我可以看到两个解决方法,none 其中看起来对我很有吸引力:

第二种选择有多糟糕?
最终目标是在以下查询中执行 Index-Only Scan

SELECT data->>'variantCode', ARRAY_AGG(product_sku)
FROM products
GROUP BY data->>'variantCode'

您不能将 data->>'variantCode' 作为 INCLUDE 列,而且将其添加为索引键不会帮助您获得仅索引扫描。 PostgreSQL 不考虑索引键不是用于仅索引扫描的列。没有根本性的问题阻止它,只是没有实现。

您必须将整个 data 添加到索引中,但这是不可能的,因为 jsonb 没有 B 树运算符 class。

因此,获得仅索引扫描的唯一剩余选项是生成的列:

ALTER TABLE products ADD data_varcode text
   GENERATED ALWAYS AS (data->>'variantCode') STORED;

然后您可以在查询和索引中使用该列。