我有一个简单的表,如下所示:| uid | search_qeury | search_ts ||-------|-----------------|-----------------------------------|| uid_1 | {\'key1&quo...
我有一张简单的表格,如下所示:
| uid | search_qeury | search_ts |
|-------|-----------------|-----------------------------------|
| uid_1 | {"key1":"val1"} | 2024-08-16 08:06:26.283557 +00:00 |
| uid_2 | {"key2":"val2"} | 2024-08-16 08:06:26.283557 +00:00 |
直接描述语言(DDL):
CREATE TABLE IF NOT EXISTS users_searches
(
uid varchar NOT NULL,
search_query json NOT NULL,
search_ts timestamptz NOT NULL
);
我需要做的是将这些值聚合到一个包含以下列的新表中: uid , searching_4h , searching_8h , searching_12h
因此我编写了一个代码来按照以下方式实现该功能:
SELECT
uid,
JSON_AGG(search_query) FILTER (WHERE search_ts > CURRENT_TIMESTAMP - INTERVAL '4' HOUR) AS searches_4h,
JSON_AGG(search_query) FILTER (WHERE search_ts > CURRENT_TIMESTAMP - INTERVAL '8' HOUR) AS searches_8h,
JSON_AGG(search_query) FILTER (WHERE search_ts > CURRENT_TIMESTAMP - INTERVAL '12' HOUR) AS searches_12h
FROM users_searches
WHERE search_ts > CURRENT_TIMESTAMP - INTERVAL '12' HOUR
GROUP BY uid
但需要大约 10 分钟才能完成。我想知道是否有更优化的方法来实现这一点。谢谢