从jsonb_each()按“值”排序数据,是否可靠?

时间:2016-12-09 11:45:18

标签: json postgresql sorting jsonb postgresql-9.5

给定jsonb类型列和数据结构如下:

{ "1": 10000.2, "2": 77.2, "3": -200.09, "4": 12.55 }

需要从此json检索结果并按VALUE

排序
SELECT * FROM jsonb_each(
 (SELECT jsonb_column FROM table WHERE id = 777)
) 
ORDER BY  VALUE  DESC 
LIMIT 100

是的,这给出了正确的结果,但问题是jsonb类型的排序有多可靠? (因为VALUEjsonb类型)。这总能正常工作吗?

我不希望(如果没有必要)显式转换:ORDER BY CAST(VALUE::TEXT AS NUMERIC)因为在json中有大约500 000个元素,并且在转换时,它需要2倍的时间,而不是仅仅按VALUE < / p>

1 个答案:

答案 0 :(得分:1)

If you don't mix data types for values that your order by, you don't need cast, if you do, it will be ordered as documented.

Object > Array > Boolean > Number > String > Null

Object with n pairs > object with n - 1 pairs

Array with n elements > array with n - 1 elements

so if you try your statement against such json:

{
  "date": "2016-10-10",
  "2": "-200.08",
  "3": -200.09,
  "some": "text", 
  "5":-200.08,
  "mt":"-200.09",
  "ar":[0,2]
}

Your get the order from above:

t=# SELECT *,pg_typeof(value) FROM jsonb_each((select a from jt where i = 7 )) order by value desc;
 key  |    value     | pg_typeof
------+--------------+-----------
 ar   | [0, 2]       | jsonb
 5    | -200.08      | jsonb
 3    | -200.09      | jsonb
 some | "text"       | jsonb
 date | "2016-10-10" | jsonb
 mt   | "-200.09"    | jsonb
 2    | "-200.08"    | jsonb
(7 rows)