PostgreSQL - 计算JSON中的元素

时间:2016-06-30 12:01:32

标签: arrays json postgresql

我有一个名为“log_data”的JSON类型列,其中存储的数据格式为[{"key":"test123123","identity":"user@test.it","identity_type":"email"}]

我想计算json中给定键的给定值的记录数:

不起作用

SELECT count (distinct esas_logs.log_id) AS "count" FROM "esas_logs" WHERE log_data->0->>'identity' = 'user@test.it'

[2016-06-30 13:59:18] [42883] ERROR: operator does not exist: json = unknown
  HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.

2 个答案:

答案 0 :(得分:3)

使用json_array_length()

test=# select  json_array_length('[{"key":"test123123","identity":"user@test.it","identity_type":"email"}]');
  json_array_length 
 -------------------
             1
 (1 row)

答案 1 :(得分:0)

根据doc,您应该使用?运算符。

如果您的列类型是JSON:

SELECT COUNT(esas_logs ? 'log_id') FROM esas_logs WHERE ...

如果您的列是TEXT或VARCHAR:

SELECT COUNT(esas_logs::jsonb ? 'log_id') FROM esas_logs WHERE ...