Introducing Dragonfly Cloud! Learn More

Redis Sorted Set List (Detailed Guide w/ Code Examples)

Use Case(s)

  • Ranking systems (e.g., leaderboards in gaming)
  • Priority queues
  • Time-series data

Code Examples

Python

import redis # Connect to Redis server client = redis.StrictRedis(host='localhost', port=6379, db=0) # Add elements to the sorted set with scores client.zadd('my_sorted_set', {'element1': 1, 'element2': 2, 'element3': 3}) # Get elements from the sorted set elements = client.zrange('my_sorted_set', 0, -1) print(elements) # Output: [b'element1', b'element2', b'element3']

Node.js

const redis = require("redis"); const client = redis.createClient(); client.on("connect", () => { console.log("Connected to Redis..."); // Add elements to the sorted set with scores client.zadd("my_sorted_set", 1, "element1", 2, "element2", 3, "element3"); // Get elements from the sorted set client.zrange("my_sorted_set", 0, -1, (err, elements) => { if (err) throw err; console.log(elements); // Output: ['element1', 'element2', 'element3'] }); });

Golang

package main import ( "fmt" "github.com/go-redis/redis/v8" "context" ) func main() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) // Add elements to the sorted set with scores rdb.ZAdd(ctx, "my_sorted_set", &redis.Z{Score: 1, Member: "element1"}, &redis.Z{Score: 2, Member: "element2"}, &redis.Z{Score: 3, Member: "element3"}) // Get elements from the sorted set elements, _ := rdb.ZRange(ctx, "my_sorted_set", 0, -1).Result() fmt.Println(elements) // Output: [element1 element2 element3] }

Common Mistakes

  • Adding elements without specifying scores can lead to unexpected behavior. Always ensure that scores are provided.
  • Overlooking the importance of connection handling. Make sure connections are properly managed and closed to avoid resource leaks.

FAQs

Q: What happens if two elements have the same score? A: Redis will sort them lexicographically by their member names.

Q: Can I update the score of an existing element? A: Yes, adding an element with an existing name but a different score will update the score for that element.

Was this content helpful?

Start building today 

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