Popular Today, This Week, This Month - Design Pattern

前端 未结 3 406
天命终不由人
天命终不由人 2021-01-02 11:23

I have a system that displays entries ordered by one of three fields, the most popular Today, This Week and This Month. Each time an entry is viewed the score is incremented

3条回答
  •  情书的邮戳
    2021-01-02 12:08

    This is actually a common problem of how to group data both effectively and keep all the necessary information.

    First of all: Did you try doing it your way? Did you really lack the storage? Your solution seems reasonable.

    How I would do it

    I assume that you are using a database for keeping the data.

    I would create two separate tables, one for hourly and one for daily statistics. Each article would have exactly 24 rows in that database, one for each hour. That would be used for hourly stats. To update a specific row you would only have to know the hour(0-23) and the entry_id. UPDATE count=count+1 WHERE hour=11 AND entry_id = 18164;

    entry_id foreign key | hour integer | count integer
    ---------------------+--------------+--------------
    1                    | 0            | 123
    1                    | 2            | 1712
    ...
    

    Current daily stats would be either computed around midnight (or whenever the app does the least) or summed on demand. Either way, once per day, a sum will have to be made of all hourly data and the sum will have to be inserted into the daily stats table.

    entry_id foreign key | day date   | count integer
    ---------------------+------------+--------------
    1                    | 2013-07-03 | 54197
    1                    | 2013-07-04 | 66123
    ...
    

    Each entry older than 31 (30/29/28) days should get deleted. Or not, if you want total or yearly statistics

    Advantages

    • you keep less data than with full hourly stats: 24+31
    • sums on hourly table should be fast, if indexed on entry_id and hour
    • less memory used than in your solution

    Disadvantages

    • additional scripting/triggers/jobs required to daily update the statistics
    • more work required to implement it than in your solution

提交回复
热议问题