skip to Main Content

I am trying to know how many new followers a company have in last 30 days. Below what I have right now:

To add each new follower:

ts = time.time()
redis_store.zadd('followers_companies:'+str(company_id_to_fav), str(current_user.id), ts)

To retrieve all followers:

followers = redis_store.zcard('followers_companies:'+str(company.id))

So, how can I I filter zcard to retrieve only results from last 30 days?

2

Answers


  1. You can use ZCOUNT to get total number of elements between the min and max. In your case max will be +inf and min will be the timestamp value of 30 days ago.

    127.0.0.1:6379> ZADD followers:1 1 a 2 b 5 c 25 d 45 e 65 f
    (integer) 6
    127.0.0.1:6379> ZCARD followers:1
    (integer) 6
    127.0.0.1:6379> ZCOUNT followers:1 35 inf
    (integer) 2
    127.0.0.1:6379> ZRANGEBYSCORE followers:1 35 inf
    1) "e"
    2) "f"
    127.0.0.1:6379>
    

    For simplicity i assumed 65 if the current timestamp and 35 is the 30 days ago. You may validate it with ZRANGEBYSCORE.

    Login or Signup to reply.
  2. To be able to do this you need to use timestamp as score. It seems like you are using user ID as score (unless the SDK you’re using has a different order for the options of ZADD).

    Then, you can use ZRANGEBYSCORE to retrieve only the last 30 days. You would use ZCOUNT if you only want to know how many, cardinality.

    ts = time.time() - 30*day
    redis_store.zcount('followers_companies:'+str(company_id_to_fav), ts, '+inf')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search