I am reading Josiah Carlson's Redis in Action.
And in the second chapter there is code like this:
conn.zadd('viewed:' + token, {item: timestamp})
conn.zremrangebyrank('viewed:' + token, 0, -26)
conn.zincrby('viewed:', -1, item) # What is this line doing ?
I just cannot understand what this line trying to do:
conn.zincrby('viewed:', -1, item)
It seems to be creating a member called -1
in the sorted-set(Zset) named viewed:
and incrementing it by the value specified in item
. Assuming item
is numerical. I have no clue why you would want to do this.
Github link to the code is here.
zincrby definition in redis-py.
Am I correct in my intuition ?
I added explanation for each command, the answer of the question is at the end.
It adds a new item(or update the score) to the specified sorted set, score as timestamp.
item
will be going to the at the end of the sorted set since timestamp is current. Therank
of this element will be the highest since it goes to the end of the list with highest score(timestamp).
conn.zadd('viewed:' + token, {item: timestamp})
It removes old items from the sorted set, keeps only most recent 25 items. The recently added
item
will not be removed if the size of sorted set is more than 25.
conn.zremrangebyrank('viewed:' + token, 0, -26)
There is also another sorted set(named
viewed:
) to keep track of all the items with their corresponding view count. Previous two commands were user(token) specific. This command is decrementing(by one) the view count of an element.
conn.zincrby('viewed:', -1, item)
If the data is modeled as put every item to a sorted set with a default score(let's say 1000) and decrement it whenever it is viewed. After that you may get the most recent products with their lowest score. (you may achieve it by incrementing all and get the reversed of the sorted)