Introducing Dragonfly Cloud! Learn More

Redis Sorted Set: Get Largest 100 (Detailed Guide w/ Code Examples)

Use Case(s)

  • Retrieve the top 100 highest-scoring elements from a leaderboard.
  • Fetch the most recent 100 log entries based on timestamps.

Code Examples

Python

To get the largest 100 elements from a sorted set:

import redis # Connect to Redis r = redis.Redis() # Example sorted set with scores sorted_set_key = 'my_sorted_set' # Get the largest 100 elements largest_100 = r.zrevrange(sorted_set_key, 0, 99, withscores=True) print(largest_100)

Node.js

To achieve the same in Node.js:

const redis = require('redis'); const client = redis.createClient(); // Example sorted set key const sortedSetKey = 'my_sorted_set'; client.zrevrange(sortedSetKey, 0, 99, 'WITHSCORES', (err, result) => { if (err) throw err; console.log(result); });

Golang

Using Go to get the largest 100 elements:

package main import ( "fmt" "github.com/go-redis/redis/v8" "context" ) func main() { rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) ctx := context.Background() sortedSetKey := "my_sorted_set" result, err := rdb.ZRevRangeWithScores(ctx, sortedSetKey, 0, 99).Result() if err != nil { panic(err) } for _, z := range result { fmt.Printf("Member: %s, Score: %f\n", z.Member, z.Score) } }

Best Practices

  • Ensure that the sorted set does not grow indefinitely by periodically removing old or irrelevant entries.
  • Use appropriate data types for scores to avoid precision issues, especially with timestamps.

Common Mistakes

  • Not handling the case when the sorted set has fewer than 100 elements, which can lead to out-of-range errors.
  • Forgetting to connect/disconnect from the Redis server properly in client libraries, leading to resource leaks.

FAQs

How do I handle cases where there are fewer than 100 elements? Most Redis clients will simply return all available elements without throwing an error. However, always check the documentation of your specific client library.

Was this content helpful?

Start building today 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.