如何找到存储在postgres列中的json大小

时间:2017-12-20 08:32:29

标签: sql json postgresql

我们正在使用Postgres。在一个表中,我们有一个JSON类型的列。

如何查找为特定行存储的JSON的大小?以及如何在该列中找到具有最大JSON数据大小的行?

3 个答案:

答案 0 :(得分:5)

如果您想知道存储列所需的字节数,那么您可以使用

  

pg_column_size(any) - 用于存储特定值的字节数   (可能是压缩的)

示例:

SELECT pg_column_size(int2) AS int2, pg_column_size(int4) AS int4,
       pg_column_size(int8) AS int8, pg_column_size(text) AS text,
       pg_column_size(bpchar) AS bpchar, pg_column_size(char) AS char,
       pg_column_size(bool) AS bool, pg_column_size(to_json) AS to_json,
       pg_column_size(to_jsonb) AS to_jsonb,
       pg_column_size(json_build_object) AS json_build_object,
       pg_column_size(jsonb_build_object) AS jsonb_build_object,
       octet_length(text) AS o_text, octet_length(bpchar) AS o_bpchar,
       octet_length(char) AS o_char, octet_length(to_json::text) AS o_to_json,
       octet_length(to_jsonb::text) AS o_to_jsonb,
       octet_length(json_build_object::text) AS o_json_build_object,
       octet_length(jsonb_build_object::text) AS o_jsonb_build_object
  FROM (SELECT 1::int2, 1::int4, 1::int8, 1::text, 1::char, '1'::"char",
        1::boolean, to_json(1), to_jsonb(1), json_build_object(1,'test'),
        jsonb_build_object(1,'test')
       ) AS sub

结果:

 int2 | int4 | int8 | text | bpchar | char | bool | to_json | to_jsonb | json_build_object | jsonb_build_object | o_text | o_bpchar | o_char | o_to_json | o_to_jsonb | o_json_build_object | o_jsonb_build_object
------+------+------+------+--------+------+------+---------+----------+-------------------+--------------------+--------+----------+--------+-----------+------------+---------------------+----------------------
    2 |    4 |    8 |    5 |      5 |    1 |    1 |       5 |       20 |                18 |                 21 |      1 |        1 |      1 |         1 |          1 |                  14 |                   13

获取具有最大json值的行只需按pg_column_size(json_column) desc limit 1排序。

答案 1 :(得分:0)

我认为:

只是想知道什么是最大的价值:

select max(pg_column_size(json)) from table;

要知道最大值的ID:

select id, pg_column_size(json)
from table
group by id
order by max(pg_column_size(json)) desc limit 1;

似乎对我有用,但我不是专家。

答案 2 :(得分:-1)

我假设您正在寻找octet_length?.. https://www.postgresql.org/docs/current/static/functions-string.html

  

字符串

中的字节数
t=# with d(j) as (values('{"a":0}'),('{"a":null}'),('{"abc":0}'))
select j,octet_length(j) from d;
     j      | octet_length
------------+--------------
 {"a":0}    |            7
 {"a":null} |           10
 {"abc":0}  |            9
(3 rows)

所以max是:

t=# with d(j) as (values('{"a":0}'),('{"a":null}'),('{"abc":0}'))
select j from d order by octet_length(j) desc limit 1;
     j
------------
 {"a":null}
(1 row)