问题描述
我有一个PostgreSQL表“ Document”,其文本列存储序列化的数据(“内容”)。有时,此内容为1 KB,有时为3 MB,依此类推。通常,我可以根据另一列(“ content_type”)对它的大小进行很好的估计。例如,如果content_type为“ history”,则内容约为1 MB。
我有一个REST端点,客户端将在其中请求缺少的文档表中的所有记录。出于记忆目的,我无法一次回复所有文档。如何限制查询,以使我一次响应一个合理的记录(比如说价值50 MB)?
我尝试为每个content_type使用UNION,以便为每个联合查询指定不同的LIMIT,但是我可能有数百种不同的content_type,因此它似乎不是一个选择。
解决方法
您可以尝试使用窗口函数来保持运行中的字节总数。在此示例中,我仅按document.id
对其进行了排序。我希望您改用某种形式的分页。
with sized as (
select *,sum(length(content)) over (order by id) as running_bytes
from document
)
select *
from sized
where running_bytes < 50 * 1024 * 1024;
要获得分页支持,我可以再增加一个CTE:
with ordered as (
select *,row_number() over (order by id) as rn
from document
),sized as (
select *,sum(length(content)) over (order by rn) as running_bytes
from ordered
where rn > <offset goes here>
)
select *
from sized
where running_bytes < 50 * 1024 * 1024;