How to query Redis Sorted Set value range with Python (with zrange)?

2023. 3. 17. 23:58it

반응형

0. What is Sorted Sets?


Sorted Sets are mainly used in places where sorting is required.

I mainly use them in Redis for querying data within a range (partially possible).

Sorted Sets consist of multiple scores and values for a single key.

Values are sorted based on their score.

Additionally, if a duplicate value is added, the existing value is updated with the new value, which can be an important issue.

In Sorted Sets, values are called members.

If you refer to the link below, you can find more detailed functions.

Let's take a look at the source code.

반응형



1. Redis connection
Redis connection input (host, port, database)

import redis

r = redis.Redis(host='localhost', port=6379, db=15)

2. Adding values to Redis zadd
zadd input: (key: {value, Score (int)})

r.zadd("tagA", {47.3: 202001010003, 182.124: 202001010004, 234.5: 202001010005})

3. Querying Redis
zrangebyscore input: (key, FromScore(int), ToScore(int))

r.zrangebyscore("tagA", "0", "(202001010002")

4. Querying Redis in reverse order
zrevrangebyscore input: (key, FromScore(int), ToScore(int))

r.zrevrangebyscore("tagA", "(202001010004", "-9999999")

5. Applying limit to Redis query
zrevrangebyscore input: (key, FromScore(int), ToScore(int), start, num)

r.zrevrangebyscore("tagA", "(202001010004", "-9999999", start=0, num=1)

728x90

6. Checking the count of zrange
zcount input: (key, FromScore(int), ToScore(int))

r.zcount("tagA", -math.inf, math.inf)

7. Deleting zrange
7-1. Finding the score to be deleted

r.zrange("tagA", 0, 0, withscores=True)
remove_data = r.zrange("tagA", 0, 0, withscores=True)[0][1]
print(remove_data)

Output: 202001010000.0

7-2. Deleting zrange
zremrangebyscore input: (key, FromScore(int), ToScore(int))

r.zremrangebyscore("tagA", remove_data, remove_data)

반응형