Improve vote count with cache
This commit is contained in:
@@ -28,6 +28,7 @@ begin
|
|||||||
count_opinion(a.id) as opinions,
|
count_opinion(a.id) as opinions,
|
||||||
zdb.score(a.ctid) _score
|
zdb.score(a.ctid) _score
|
||||||
from article as a
|
from article as a
|
||||||
|
left join vote_cache ca using (id)
|
||||||
where (
|
where (
|
||||||
_search is null
|
_search is null
|
||||||
or _search = ''
|
or _search = ''
|
||||||
@@ -43,8 +44,8 @@ begin
|
|||||||
case sort
|
case sort
|
||||||
when 'title' then a.title
|
when 'title' then a.title
|
||||||
when 'created_at' then a.created_at::text
|
when 'created_at' then a.created_at::text
|
||||||
when 'vote' then count_vote(a.id)->>'score'
|
when 'vote' then ca.score::text
|
||||||
when 'popularity' then count_vote(a.id)->>'total'
|
when 'popularity' then ca.total::text
|
||||||
else null
|
else null
|
||||||
end
|
end
|
||||||
end,
|
end,
|
||||||
@@ -52,8 +53,8 @@ begin
|
|||||||
case sort
|
case sort
|
||||||
when 'title' then a.title
|
when 'title' then a.title
|
||||||
when 'created_at' then a.created_at::text
|
when 'created_at' then a.created_at::text
|
||||||
when 'vote' then count_vote(a.id)->>'score'
|
when 'vote' then ca.score::text
|
||||||
when 'popularity' then count_vote(a.id)->>'total'
|
when 'popularity' then ca.total::text
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
desc,
|
desc,
|
||||||
|
|||||||
@@ -35,6 +35,19 @@ begin
|
|||||||
end if;
|
end if;
|
||||||
|
|
||||||
select count_vote(_target_id) into resource;
|
select count_vote(_target_id) into resource;
|
||||||
|
|
||||||
|
insert into vote_cache (id, total, score, percent) values
|
||||||
|
(
|
||||||
|
_target_id,
|
||||||
|
(resource->>'total')::int,
|
||||||
|
(resource->>'score')::int,
|
||||||
|
(resource->>'percent')::int
|
||||||
|
)
|
||||||
|
on conflict (id) do update set
|
||||||
|
updated_at = now(),
|
||||||
|
total = excluded.total,
|
||||||
|
score = excluded.score,
|
||||||
|
percent = excluded.percent;
|
||||||
end;
|
end;
|
||||||
$$;
|
$$;
|
||||||
|
|
||||||
|
|||||||
@@ -495,6 +495,20 @@ create table vote_for_comment_on_constitution
|
|||||||
unique (created_by_id, target_id)
|
unique (created_by_id, target_id)
|
||||||
) inherits (vote);
|
) inherits (vote);
|
||||||
|
|
||||||
|
|
||||||
|
create table vote_cache
|
||||||
|
(
|
||||||
|
id uuid not null primary key,
|
||||||
|
updated_at timestamp not null default now(),
|
||||||
|
total int not null default 0,
|
||||||
|
score int not null default 0,
|
||||||
|
percent int not null default 0
|
||||||
|
);
|
||||||
|
|
||||||
|
create index on vote_cache (total);
|
||||||
|
create index on vote_cache (score);
|
||||||
|
create index on vote_cache (percent);
|
||||||
|
|
||||||
-- Stats
|
-- Stats
|
||||||
create table resource_view
|
create table resource_view
|
||||||
(
|
(
|
||||||
|
|||||||
Reference in New Issue
Block a user