从Postgresql请求格式化JSON表

时间:2017-02-21 15:47:04

标签: ruby-on-rails json postgresql

我正在尝试从postgresql请求创建一个Json格式。

首先,我使用Rails在我的控制器的 format.json 块中请求我的数据库,然后使用 json.builder 文件格式化json视图。它一直工作,直到我的请求返回数十万行,所以我搜索了如何优化json创建,避免所有的ActiveRecord堆栈。

为此,我使用Postgresql 9.6 json函数以正确的格式直接获取数据,例如:

SELECT array_to_json('{{1157241840,-1.95},{1157241960,-1.96}}'::float[]);
[[1157241840, -1.95], [1157241960, -1.96]]

但是使用来自此类请求的数据:

SELECT date,value FROM measures;

我能获得的最好成绩是这样的:

SELECT array_to_json(array_agg(t)) FROM (SELECT date,value FROM measures) t;

导致:

[
 {"date":"1997-06-13T19:12:00","value":1608.4},
 {"date":"1997-06-13T19:12:00","value":-0.6}
]

这是完全不同的......你将如何构建这个SQL请求?
谢谢你的帮助!

我的度量表如下所示:

      id | value |          created_at        |         updated_at         | parameter_id | quality_id | station_id |          date       | campain_id | elevation | sensor_id | comment_id  
 --------+-------+----------------------------+----------------------------+--------------+------------+------------+---------------------+------------+-----------+-----------+------------
  799634 | -1.99 | 2017-02-21 09:41:09.062795 | 2017-02-21 09:41:09.118807 |            2 |            |          1 | 2006-06-26 23:24:00 |          1 |      -5.0 |           |
 1227314 | -1.59 | 2017-02-21 09:44:12.032576 | 2017-02-21 09:44:12.088311 |            2 |            |          1 | 2006-11-30 19:48:00 |          1 |      -5.0 |           |           
 1227315 | 26.65 | 2017-02-21 09:44:12.032576 | 2017-02-21 09:44:12.088311 |            3 |            |          1 | 2006-11-30 19:48:00 |          1 |      -5.0 |           |           

2 个答案:

答案 0 :(得分:1)

如果需要数组数组,则需要使用json_build_array:

SELECT json_agg(json_build_array(date,value)) FROM measures;

如果您想将时间戳转换为纪元:

SELECT json_agg(json_build_array(extract(epoch FROM date)::int8, value)) FROM measures;

进行测试:

WITH measures AS (
    SELECT 1157241840 as date, -1.95 as value
     UNION SELECT 1157241960, -1.96
     UNION SELECT 1157241980, NULL
) 


SELECT json_agg(json_build_array(date,value)) FROM measures;


                            json_agg                            
----------------------------------------------------------------
 [[1157241840, -1.95], [1157241960, -1.96], [1157241980, null]]

答案 1 :(得分:0)

create table measures (date timestamp, value float);
insert into measures (date, value) values
(to_timestamp(1157241840),-1.95),
(to_timestamp(1157241960),-1.96);

select array_to_json(array_agg(array[extract(epoch from date), value]::float[]))
from measures
;
              array_to_json              
-----------------------------------------
 [[1157241840,-1.95],[1157241960,-1.96]]