Redis Sorted Set: Score (Detailed Guide w/ Code Examples)
Use Case(s)
- Ranking players in a game by their scores.
- Sorting articles by their publication dates.
- Prioritizing tasks by urgency in a task management application.
Code Examples
Adding Members with Scores
To add members to a sorted set with scores, use the ZADD
command.
Python
import redis r = redis.StrictRedis(host='localhost', port=6379, db=0) r.zadd('myset', {'member1': 10, 'member2': 20})
Node.js
const redis = require('redis'); const client = redis.createClient(); client.zadd('myset', 10, 'member1'); client.zadd('myset', 20, 'member2');
Golang
package main import ( "github.com/go-redis/redis/v8" "context" ) func main() { rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) ctx := context.Background() rdb.ZAdd(ctx, "myset", &redis.Z{Score: 10, Member: "member1"}, &redis.Z{Score: 20, Member: "member2"}) }
Retrieving Members by Score Range
To retrieve members within a specific score range, use the ZRANGEBYSCORE
command.
Python
members = r.zrangebyscore('myset', 10, 20) print(members) # Output: [b'member1', b'member2']
Node.js
client.zrangebyscore('myset', 10, 20, (err, res) => { if (err) throw err; console.log(res); // Output: ['member1', 'member2'] });
Golang
members, err := rdb.ZRangeByScore(ctx, "myset", &redis.ZRangeBy{ Min: "10", Max: "20", }).Result() if err != nil { panic(err) } fmt.Println(members) // Output: [member1 member2]
Best Practices
- When adding members, batch operations together to minimize network overhead.
- Use meaningful and unique member identifiers to avoid conflicts.
- Monitor and optimize memory usage as sorted sets can grow large.
Common Mistakes
- Forgetting to convert scores to float values when using certain languages or libraries.
- Not handling network errors which can cause incomplete data operations.
- Overlooking Redis persistence settings, leading to potential data loss on crashes.
FAQs
Q: How do I update the score of an existing member?
A: Use the ZADD
command again with the new score. If the member exists, its score will be updated.
Q: What happens if two members have the same score?
A: Members with the same score are ordered lexicographically by their member names.
Was this content helpful?
Similar Code Examples
- Redis Sorted Set: Delete
- Redis Sorted Set: Get Highest Score
- Redis Sorted Set List
- 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 Dump
- Redis Sorted Set: Replace Element
Start building today
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.