Redis Sorted Set: Count (Detailed Guide w/ Code Examples)

Use Case(s)

  • Counting the number of elements within a specific score range in a sorted set.
  • Monitoring the number of users or items that fall within certain thresholds, such as scores or ranking.

Code Examples

Python

Using the zcount command in Python with the redis-py library:

import redis r = redis.Redis(host='localhost', port=6379, db=0) r.zadd('myzset', {'one': 1, 'two': 2, 'three': 3}) # Count elements with scores between 1 and 2 (inclusive) count = r.zcount('myzset', 1, 2) print(count) # Output: 2

Node.js

Using the zcount command in Node.js with the ioredis library:

const Redis = require('ioredis'); const redis = new Redis(); redis.zadd('myzset', 1, 'one', 2, 'two', 3, 'three'); redis.zcount('myzset', 1, 2).then((count) => { console.log(count); // Output: 2 });

Golang

Using the ZCount method with the go-redis package:

package main import ( "fmt" "github.com/go-redis/redis/v8" "context" ) func main() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) rdb.ZAdd(ctx, "myzset", &redis.Z{Score: 1, Member: "one"}) rdb.ZAdd(ctx, "myzset", &redis.Z{Score: 2, Member: "two"}) rdb.ZAdd(ctx, "myzset", &redis.Z{Score: 3, Member: "three"}) count, err := rdb.ZCount(ctx, "myzset", "1", "2").Result() if err != nil { panic(err) } fmt.Println(count) // Output: 2 }

Best Practices

  • Ensure score ranges are properly defined to include/exclude boundaries as required.
  • Use inclusive and exclusive ranges appropriately based on your data needs.

Common Mistakes

  • Misunderstanding score range boundaries. For example, using (1,2) instead of [1,2] might lead to off-by-one errors.

FAQs

What does the zcount command do? It counts the number of elements in a sorted set with scores within the specified range.

Can I use zcount with negative scores? Yes, zcount works with any floating-point score values, including negative numbers.

Was this content helpful?

Start building today

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