How to get same rank for same scores in Redis' ZRANK?

后端 未结 4 1537
灰色年华
灰色年华 2020-12-20 22:54

If I have 5 members with scores as follows

a - 1
b - 2
c - 3
d - 3
e - 5

ZRANK of c returns 2, ZRANK of d returns 3

Is there a way

4条回答
  •  时光取名叫无心
    2020-12-20 23:39

    You can achieve the goal with two Sorted Set: one for member to score mapping, and one for score to rank mapping.

    Add

    1. Add items to member to score mapping: ZADD mem_2_score 1 a 2 b 3 c 3 d 5 e
    2. Add the scores to score to rank mapping: ZADD score_2_rank 1 1 2 2 3 3 5 5

    Search

    1. Get score first: ZSCORE mem_2_score c, this should return the score, i.e. 3.
    2. Get the rank for the score: ZRANK score_2_rank 3, this should return the dense ranking, i.e. 2.

    In order to run it atomically, wrap the Add, and Search operations into 2 Lua scripts.

提交回复
热议问题