如何提高PostgreSQL数据库中海量数据的查询效率?

How to increase query efficiency for a large volume of data in a PostgreSQL database?

我有一个包含 12 亿行 的 PostgreSQL 数据库,试图制作一个一次查询一百万行的应用程序,并可以选择查询更大的间隔。 起初我只是轻松地查询一个 百万到 1000 万 的数据库;
现在我正在使用 OFFSET 查询大型数据库,ResultSet 需要很长时间才能生成。

   // ...
   stmt.setFetchSize(100000);
   ResultSet rs = stmt.executeQuery("SELECT mmsi, report_timestamp, position_geom, ST_X(position_geom) AS Long, "
                        + "ST_Y(position_geom) AS Lat FROM reports4 WHERE position_geom IS NOT NULL ORDER by report_timestamp ASC LIMIT "
                        + limit + " OFFSET " + set); 

所以 ORDER BY 可能会占用我的执行时间,但是对信息进行排序会让以后的事情变得更容易。有没有更有效的方法来按间隔查询行?

对于此查询:

SELECT mmsi, report_timestamp, position_geom, ST_X(position_geom) AS Long, "
                        + "ST_Y(position_geom) AS Lat
FROM reports4
WHERE position_geom IS NOT NULL
ORDER by report_timestamp ASC;

您应该能够在表达式上使用索引:

CREATE INDEX idx_reports4_position_ts ON reports4((position_geom IS NOT NULL), report_timestamp)

该索引应该直接用于查询。

您可以使用基于数据库子集构建的部分索引。

CREATE INDEX idx_reports4 ON reports4(position_geom, report_timestamp) where position_geom IS NOT NULL;

这会大大提高性能,因为您只是在索引所需的数据库的一部分。