我们可以为 JSONB 数据类型的键/值创建索引吗?

Kok*_*zzu 5 postgresql performance index postgresql-9.4 postgresql-performance

我们可以为 JSONB 数据类型的键/值创建索引吗?

例如,对于这些架构:

CREATE TABLE x (
  id BIGSERIAL,
  data JSONB
);
CREATE TABLE y (
  id BIGSERIAL,
  data JSONB
);
Run Code Online (Sandbox Code Playgroud)

慢查询:

SELECT *
FROM x
  LEFT JOIN y
    ON (y.data->>'x_id')::BIGINT = x.id
Run Code Online (Sandbox Code Playgroud)

如何为该索引创建y.data->>'x_id'可用于此类查询的索引?

Erw*_*ter 6

我建议在键 'x_id' 的值上使用表达式索引,强制转换为bigint- 普通(默认)btree,而不是 GIN。这里有一个特殊的困难:类型转换的简短表示法需要多层括号才能使语法适用于索引创建。

CREATE INDEX y_data_xid_idx ON y (((y.data->>'x_id')::bigint));
Run Code Online (Sandbox Code Playgroud)

而是使用显式形式(达到相同的效果):

CREATE INDEX y_data_xid_idx ON y (cast(y.data->>'x_id' AS bigint));
Run Code Online (Sandbox Code Playgroud)

  • 是否可以使用动态键将这样的索引添加到 JSONB 字段? (4认同)