← 中文资源

简体中文版本

EXP 衰减趋势分

用 EXP 指数衰减与 gravity 分母两种口径给帖子打时效分:新票权重高、旧帖自然下沉,按衰减分 ORDER BY 即得趋势榜单。

阅读英文原文

实现说明

这个文件依次执行 SELECT / INSERT / CREATE 语句,涉及 posts。 逐子句看,这些语句使用了:ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY。

常见问题

这里用到哪些关系?

posts——直接引用,无需连接。

核心语句

INSERT INTO posts (post_id, title, votes, posted_at) VALUES
    (1, 'fresh launch', 40, now() - INTERVAL '1 hour'),
    (2, 'yesterday hit', 400, now() - INTERVAL '26 hours'),
    (3, 'last week recap', 900, now() - INTERVAL '7 days');
SELECT post_id, title, votes,
       ROUND(votes / POWER(EXTRACT(EPOCH FROM (now() - posted_at)) / 3600.0 + 2, 1.5)::numeric, 3) AS gravity_score
FROM posts
ORDER BY gravity_score DESC;
SELECT post_id, title,
       ROUND(votes * EXP(-EXTRACT(EPOCH FROM (now() - posted_at)) / 21600.0)::numeric, 3) AS decay_score
FROM posts
ORDER BY decay_score DESC;

代码示例

-- time-decay ranking for trending feeds: gravity denominator vs exponential decay
CREATE TABLE posts (
    post_id   int PRIMARY KEY,
    title     text NOT NULL,
    votes     int NOT NULL,
    posted_at timestamptz NOT NULL
);

INSERT INTO posts (post_id, title, votes, posted_at) VALUES
    (1, 'fresh launch', 40, now() - INTERVAL '1 hour'),
    (2, 'yesterday hit', 400, now() - INTERVAL '26 hours'),
    (3, 'last week recap', 900, now() - INTERVAL '7 days');

-- gravity denominator: (age_hours + 2)^1.5 -- the older the item, the lower the score
SELECT post_id, title, votes,
       ROUND(votes / POWER(EXTRACT(EPOCH FROM (now() - posted_at)) / 3600.0 + 2, 1.5)::numeric, 3) AS gravity_score
FROM posts
ORDER BY gravity_score DESC;

-- exponential decay: votes * exp(-age_hours / 6) -- tau = 6 hours, a faster forgetting curve
SELECT post_id, title,
       ROUND(votes * EXP(-EXTRACT(EPOCH FROM (now() - posted_at)) / 21600.0)::numeric, 3) AS decay_score
FROM posts
ORDER BY decay_score DESC;