postgresql在where子句中使用json子元素

这可能是一个非常基本的问题,但我无法在网上找到任何内容.

如果我创建一个示例表:

create table dummy ( id int not null,data json );

然后,如果我使用以下查询查询表

select * from dummy where data->'x' = 10;

现在,由于表中没有记录,并且在任何记录中都没有“x”的属性,所以应该返回零结果.

但是我收到以下错误

postgres=# select * from dummy where data->'x' = 10;
ERROR:  operator does not exist: json = integer
LINE 1: select * from dummy where data->'x' = 10;

但以下查询工作:

select * from dummy where cast(data->>'x' as integer) = 10;

在这里缺少某些东西,或者是类型转换是从json字段获得整数值的唯一方法?如果是这样,当数据变得非常大时,不会影响性能

Am I missing something here or typecasting is the only way I can get
an integer value from a json field ?

你是正确的,类型转换是从json字段读取整数值的唯一方法.

If that’s the case,does it not affect the performance when data
becomes extremely large ?

Postgres允许您对包括转换的索引功能进行索引,因此下面的索引将允许您快速检索data->> x具有某个整数值的所有行

CREATE INDEX dummy_x_idx ON dummy(cast("data"->>'x' AS int))

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...