如何在 postgres 中的整数 json 属性上创建索引

Chr*_*oph 8 postgresql index cast postgresql-9.3 json

我一生都无法弄清楚如何在我的 json 列的整数属性上创建索引。

我以这种方式尝试过(以及其他数十种方式)

CREATE INDEX user_reputation_idx ON users(("user"->>'reputation')::int)
Run Code Online (Sandbox Code Playgroud)

它在查询中工作得很好(例如ORDER BY ("user"->>'reputation')::int

我错过了什么?

更新

我收到一个简单的语法错误,但是,我真的不知道为什么。

ERROR:  syntax error at or near "::"
LINE 1: ... user_reputation_idx ON users (("user"->>'reputation')::int)
Run Code Online (Sandbox Code Playgroud)

表定义非常简单。它只是一列usertype json

所以,看起来像这样:

CREATE TABLE users
(
  "user" json
)
Run Code Online (Sandbox Code Playgroud)

Erw*_*ter 14

试试这个:

CREATE INDEX user_reputation_idx ON users(cast("user"->>'reputation' AS int));
Run Code Online (Sandbox Code Playgroud)

如果索引定义中没有附加括号,则不允许使用Postgres 语法快捷方式::进行转换请参阅 @bma 的评论)。不过,它适用于标准 SQL 函数:cast(expression AS type)这与json类型本身无关。

无论哪种方式,您仍然可以在expression::type使用索引的表达式中使用语法快捷方式。

  • 有了足够的括号,它应该可以工作。例如`CREATE INDEX user_reputation_idx2 ON users ((("user"->>'reputation')::INT))`。我记得读过 pg 列表中的一个答案,其中 Tom Lane 解释了为什么表达式需要额外的括号,但快速搜索没有找到。 (6认同)