postgresql – 如何分组/选择JSON类型列(PG :: UndefinedFunction:ERROR:无法识别json类型的相等运算符)

我想做

<MODEL>.select("brief_content").group("brief_content")

这是表格方案,

:id => :integer,:content => :json,:brief_content => :json

但我得到了错误,

我该怎么办,谢谢

companyAlarmlog Load (0.9ms)  SELECT company_alarm_logs.id,company_alarm_logs.name,company_alarm_logs.utc_time,company_alarm_logs.company_alarm_test_id,company_alarm_logs.brief_content,brief_content FROM "company_alarm_logs" GROUP BY brief_content ORDER BY utc_time
E,[2014-06-24T09:40:39.069988 #954] ERROR -- : PG::UndefinedFunction: ERROR:  Could not identify an equality operator for type json
LINE 1: ...t,brief_content FROM "company_alarm_logs"  GROUP BY brief_cont...
                                                             ^
: SELECT company_alarm_logs.id,brief_content FROM "company_alarm_logs"  GROUP BY brief_content  ORDER BY utc_time
Hirb Error: PG::UndefinedFunction: ERROR:  Could not identify an equality operator for type json
LINE 1: ...t,brief_content FROM "company_alarm_logs"  GROUP BY brief_cont...

解决方法

不幸的是,没有简单的方法可以在9.3中直接进行json相等测试.

9.3的json类型没有相等运算符,因为它接受带有重复键的json(正如许多实现所期望的那样).目前尚不清楚{“a”:1,“a”:2}是否与{“a”:1}“相等”.

9.4添加了jsonb,它在最后一键获胜的基础上折叠重复键,使得相等无误.

regress=# SELECT '{"a":1,"a":2}'::json = '{"a":1}'::json;
ERROR:  operator does not exist: json = json
LINE 1: SELECT '{"a":1,"a":2}'::json = '{"a":1}'::json;
                                      ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

regress=# SELECT '{"a":1,"a":2}'::jsonb = '{"a":1}'::jsonb;
 ?column? 
----------
 f
(1 row)

不幸的是,这意味着你无法在9.3中完成你想做的事.

你可以为json编写一个自定义相等运算符 – 也许只是将两者都转换为文本并比较那种方式,但是它会对待{“a”:1,“b”:2}和{“b”:2,“a” :1}不平等.

更好的选择是安装PL / V8并使用V8 JavaScript引擎的json操作来执行相等比较.

为json定义一个等于运算符,然后使用该运算符定义一个简单的b-tree opclass.两者在sql级别都很简单 – 请参阅CREATE OPERATOR和CREATE OPERATOR CLASS.

完成后,您将能够在9.3中使用GROUP BY json值.

或者你可以安装9.4 beta1并使用jsonb.

相关文章

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