Dragonfly

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

Use Case(s)

Code Examples

To add an element to a sorted set with an expiration time (TTL):

Python

import redis
import time

client = redis.StrictRedis(host='localhost', port=6379, db=0)

# Add an element to the sorted set
client.zadd('myset', {'element': 1})

# Set TTL for the sorted set
client.expire('myset', 60)  # Expires in 60 seconds

# Example to verify the TTL
ttl = client.ttl('myset')
print(f"TTL of myset: {ttl} seconds")

Node.js

const redis = require('redis');
const client = redis.createClient();

client.on('connect', () => {
    console.log('Connected to Redis...');
    
    // Add an element to the sorted set
    client.zadd('myset', 1, 'element', (err, res) => {
        if (err) throw err;
        
        // Set TTL for the sorted set
        client.expire('myset', 60, (err, res) => {
            if (err) throw err;
            
            // Get TTL of the sorted set
            client.ttl('myset', (err, ttl) => {
                if (err) throw err;
                console.log(`TTL of myset: ${ttl} seconds`);
                client.quit();
            });
        });
    });
});

Golang

package main

import (
	"fmt"
	"time"

	"github.com/go-redis/redis/v8"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})

	// Add an element to the sorted set
	client.ZAdd(ctx, "myset", &redis.Z{
		Score:  1,
		Member: "element",
	})

	// Set TTL for the sorted set
	client.Expire(ctx, "myset", 60*time.Second)

	// Example to verify the TTL
	ttl, _ := client.TTL(ctx, "myset").Result()
	fmt.Printf("TTL of myset: %v\n", ttl)
}

Best Practices

Common Mistakes

FAQs

Q: Can I set a TTL on individual elements within a sorted set?
A: No, Redis does not support setting TTLs on individual elements within a sorted set, only on the entire set.

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