Redis Sorted Set: Remove by Score (Detailed Guide w/ Code Examples)
Use Case(s)
Removing elements from a Redis Sorted Set based on their scores is useful when managing time-sensitive data, such as expiring cache entries, removing outdated records, or trimming leaderboards.
Code Examples
Python
import redis client = redis.StrictRedis(host='localhost', port=6379, db=0) # Add some elements with scores client.zadd('myset', {'member1': 10, 'member2': 20, 'member3': 30}) # Remove all elements with scores between 15 and 25 (inclusive) client.zremrangebyscore('myset', 15, 25)
Node.js
const redis = require('redis'); const client = redis.createClient(); client.zadd('myset', 10, 'member1'); client.zadd('myset', 20, 'member2'); client.zadd('myset', 30, 'member3'); client.zremrangebyscore('myset', 15, 25, (err, response) => { if (err) throw err; console.log(response); // Number of members removed });
Golang
package main import ( "fmt" "github.com/go-redis/redis/v8" "context" ) func main() { ctx := context.Background() client := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) client.ZAdd(ctx, "myset", &redis.Z{Score: 10, Member: "member1"}) client.ZAdd(ctx, "myset", &redis.Z{Score: 20, Member: "member2"}) client.ZAdd(ctx, "myset", &redis.Z{Score: 30, Member: "member3"}) client.ZRemRangeByScore(ctx, "myset", "15", "25") }
Best Practices
- Always handle possible errors when working with Redis operations.
- Make use of transactions (
MULTI
/EXEC
) if multiple operations depend on each other to maintain atomicity.
Common Mistakes
- Not converting score ranges to string when required in certain languages or libraries (e.g., Go).
- Forgetting to check the number of removed elements to ensure the operation's success.
FAQs
Q: What happens if there are no elements within the specified score range? A: The command will simply return 0, indicating no elements were removed.
Q: Can score ranges be inclusive/exclusive?
A: Yes, you can specify inclusive ranges using [min,max]
and exclusive ranges using (min,max)
.
Was this content helpful?
Similar Code Examples
- Redis Sorted Set: Get Highest Score
- Redis Sorted Set: Create
- Redis Sorted Set: Get by Key
- Redis Sorted Set: Limit Size
- Redis Sorted Set: Same Score
- Redis Sorted Set: Sorting by Multiple Fields
- Redis Sorted Set TTL
- Redis Sorted Set: Sort by Date
- Redis Sorted Set: Expire Key
- Redis Sorted Set: Check Exists
- Redis Sorted Set: Rate Limit
- Redis Sorted Set: Custom Order
Switch & save up to 80%
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost