Dragonfly

Redis Sorted Set: Get Highest Score (Detailed Guide w/ Code Examples)

Use Case(s)

Code Examples

Python

Using the zrevrange command to get the member with the highest score:

import redis

r = redis.Redis(host='localhost', port=6379, db=0)
highest_score_member = r.zrevrange('my_sorted_set', 0, 0, withscores=True)
print(highest_score_member)

Node.js

Using the zrevrange command with the ioredis library:

const Redis = require('ioredis');
const redis = new Redis();

redis.zrevrange('my_sorted_set', 0, 0, 'WITHSCORES').then((result) => {
    console.log(result);
});

Golang

Using the ZRANGE command with the go-redis library:

package main

import (
    "fmt"
    "github.com/go-redis/redis/v8"
    "context"
)

func main() {
    ctx := context.Background()
    rdb := redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
    })
    result, err := rdb.ZRevRangeWithScores(ctx, "my_sorted_set", 0, 0).Result()
    if err != nil {
        panic(err)
    }
    fmt.Println(result)
}

Best Practices

Common Mistakes

FAQs

Q: What is the difference between ZRANGE and ZREVRANGE?
A: ZRANGE retrieves elements in ascending order by score, while ZREVRANGE retrieves them in descending order.

Q: How can I efficiently remove the highest score after retrieving it?
A: Use a transaction (MULTI/EXEC) to ensure atomicity when getting and removing the element with the highest score.

Was this content helpful?

Similar Code Examples

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

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