Redis sorted sets
Introduction to Redis sorted sets
A Redis sorted set is a collection of unique strings (members) ordered by an associated score. When more than one string has the same score, the strings are ordered lexicographically. Some use cases for sorted sets include:
- Leaderboards. For example, you can use sorted sets to easily maintain ordered lists of the highest scores in a massive online game.
- Rate limiters. In particular, you can use a sorted set to build a sliding-window rate limiter to prevent excessive API requests.
You can think of sorted sets as a mix between a Set and a Hash. Like sets, sorted sets are composed of unique, non-repeating string elements, so in some sense a sorted set is a set as well.
However while elements inside sets are not ordered, every element in a sorted set is associated with a floating point value, called the score (this is why the type is also similar to a hash, since every element is mapped to a value).
Moreover, elements in a sorted set are taken in order (so they are not ordered on request, order is a peculiarity of the data structure used to represent sorted sets). They are ordered according to the following rule:
- If B and A are two elements with a different score, then A > B if A.score is > B.score.
- If B and A have exactly the same score, then A > B if the A string is lexicographically greater than the B string. B and A strings can't be equal since sorted sets only have unique elements.
Let's start with a simple example, we'll add all our racers and the score they got in the first race:
> ZADD racer_scores 10 "Norem"
(integer) 1
> ZADD racer_scores 12 "Castilla"
(integer) 1
> ZADD racer_scores 8 "Sam-Bodden" 10 "Royce" 6 "Ford" 14 "Prickett"
(integer) 4
"""
Code samples for Sorted set doc pages:
https://redis.io/docs/latest/develop/data-types/sorted-sets/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.zadd("racer_scores", {"Norem": 10})
print(res1) # >>> 1
res2 = r.zadd("racer_scores", {"Castilla": 12})
print(res2) # >>> 1
res3 = r.zadd(
"racer_scores",
{"Sam-Bodden": 8, "Royce": 10, "Ford": 6, "Prickett": 14, "Castilla": 12},
)
print(res3) # >>> 4
res4 = r.zrange("racer_scores", 0, -1)
print(res4) # >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce', 'Castilla', 'Prickett']
res5 = r.zrevrange("racer_scores", 0, -1)
print(res5) # >>> ['Prickett', 'Castilla', 'Royce', 'Norem', 'Sam-Bodden', 'Ford']
res6 = r.zrange("racer_scores", 0, -1, withscores=True)
print(
res6
)
# >>> [
# ('Ford', 6.0), ('Sam-Bodden', 8.0), ('Norem', 10.0), ('Royce', 10.0),
# ('Castilla', 12.0), ('Prickett', 14.0)
# ]
res7 = r.zrangebyscore("racer_scores", "-inf", 10)
print(res7) # >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce']
res8 = r.zrem("racer_scores", "Castilla")
print(res8) # >>> 1
res9 = r.zremrangebyscore("racer_scores", "-inf", 9)
print(res9) # >>> 2
res10 = r.zrange("racer_scores", 0, -1)
print(res10) # >>> ['Norem', 'Royce', 'Prickett']
res11 = r.zrank("racer_scores", "Norem")
print(res11) # >>> 0
res12 = r.zrevrank("racer_scores", "Norem")
print(res12) # >>> 2
res13 = r.zadd(
"racer_scores",
{
"Norem": 0,
"Sam-Bodden": 0,
"Royce": 0,
"Ford": 0,
"Prickett": 0,
"Castilla": 0,
},
)
print(res13) # >>> 3
res14 = r.zrange("racer_scores", 0, -1)
print(res14) # >>> ['Castilla', 'Ford', 'Norem', 'Prickett', 'Royce', 'Sam-Bodden']
res15 = r.zrangebylex("racer_scores", "[A", "[L")
print(res15) # >>> ['Castilla', 'Ford']
res16 = r.zadd("racer_scores", {"Wood": 100})
print(res16) # >>> 1
res17 = r.zadd("racer_scores", {"Henshaw": 100})
print(res17) # >>> 1
res18 = r.zadd("racer_scores", {"Henshaw": 150})
print(res18) # >>> 0
res19 = r.zincrby("racer_scores", 50, "Wood")
print(res19) # >>> 150.0
res20 = r.zincrby("racer_scores", 50, "Henshaw")
print(res20) # >>> 200.0
import assert from 'assert';
import { createClient } from 'redis';
const client = createClient();
await client.connect();
const res1 = await client.zAdd('racer_scores', { score: 10, value: 'Norem' });
console.log(res1); // >>> 1
const res2 = await client.zAdd('racer_scores', { score: 12, value: 'Castilla' });
console.log(res2); // >>> 1
const res3 = await client.zAdd('racer_scores', [
{ score: 8, value: 'Sam-Bodden' },
{ score: 10, value: 'Royce' },
{ score: 6, value: 'Ford' },
{ score: 14, value: 'Prickett' },
{ score: 12, value: 'Castilla' }
]);
console.log(res3); // >>> 4
const res4 = await client.zRange('racer_scores', 0, -1);
console.log(res4); // >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce', 'Castilla', 'Prickett']
const res6 = await client.zRangeWithScores('racer_scores', 0, -1);
console.log(res6);
// >>> [
// { value: 'Ford', score: 6 }, { value: 'Sam-Bodden', score: 8 },
// { value: 'Norem', score: 10 }, { value: 'Royce', score: 10 },
// { value: 'Castilla', score: 12 }, { value: 'Prickett', score: 14 }
// ]
const res7 = await client.zRangeByScore('racer_scores', '-inf', 10);
console.log(res7); // >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce']
const res8 = await client.zRem('racer_scores', 'Castilla');
console.log(res8); // >>> 1
const res9 = await client.zRemRangeByScore('racer_scores', '-inf', 9);
console.log(res9); // >>> 2
const res10 = await client.zRange('racer_scores', 0, -1);
console.log(res10); // >>> ['Norem', 'Royce', 'Prickett']
const res11 = await client.zRank('racer_scores', 'Norem');
console.log(res11); // >>> 0
const res12 = await client.zRevRank('racer_scores', 'Norem');
console.log(res12); // >>> 2
const res13 = await client.zAdd('racer_scores', [
{ score: 0, value: 'Norem' },
{ score: 0, value: 'Sam-Bodden' },
{ score: 0, value: 'Royce' },
{ score: 0, value: 'Ford' },
{ score: 0, value: 'Prickett' },
{ score: 0, value: 'Castilla' }
]);
console.log(res13); // >>> 3
const res14 = await client.zRange('racer_scores', 0, -1);
console.log(res14); // >>> ['Castilla', 'Ford', 'Norem', 'Prickett', 'Royce', 'Sam-Bodden']
const res15 = await client.zRangeByLex('racer_scores', '[A', '[L');
console.log(res15); // >>> ['Castilla', 'Ford']
const res16 = await client.zAdd('racer_scores', { score: 100, value: 'Wood' });
console.log(res16); // >>> 1
const res17 = await client.zAdd('racer_scores', { score: 100, value: 'Henshaw' });
console.log(res17); // >>> 1
const res18 = await client.zAdd('racer_scores', { score: 150, value: 'Henshaw' }, { nx: true });
console.log(res18); // >>> 0
const res19 = await client.zIncrBy('racer_scores', 50, 'Wood');
console.log(res19); // >>> 150.0
const res20 = await client.zIncrBy('racer_scores', 50, 'Henshaw');
console.log(res20); // >>> 200.0
package io.redis.examples;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.resps.Tuple;
public class SortedSetsExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
long res1 = jedis.zadd("racer_scores", 10d, "Norem");
System.out.println(res1); // >>> 1
long res2 = jedis.zadd("racer_scores", 12d, "Castilla");
System.out.println(res2); // >>> 1
long res3 = jedis.zadd("racer_scores", new HashMap<String,Double>() {{
put("Sam-Bodden", 8d);
put("Royce", 10d);
put("Ford", 6d);
put("Prickett", 14d);
put("Castilla", 12d);
}});
System.out.println(res3); // >>> 4
List<String> res4 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res4); // >>> [Ford, Sam-Bodden, Norem, Royce, Castil, Castilla, Prickett]
List<String> res5 = jedis.zrevrange("racer_scores", 0, -1);
System.out.println(res5); // >>> [Prickett, Castilla, Castil, Royce, Norem, Sam-Bodden, Ford]
List<Tuple> res6 = jedis.zrangeWithScores("racer_scores", 0, -1);
System.out.println(res6); // >>> [[Ford,6.0], [Sam-Bodden,8.0], [Norem,10.0], [Royce,10.0], [Castil,12.0], [Castilla,12.0], [Prickett,14.0]]
List<String> res7 = jedis.zrangeByScore("racer_scores", Double.MIN_VALUE, 10d);
System.out.println(res7); // >>> [Ford, Sam-Bodden, Norem, Royce]
long res8 = jedis.zrem("racer_scores", "Castilla");
System.out.println(res8); // >>> 1
long res9 = jedis.zremrangeByScore("racer_scores", Double.MIN_VALUE, 9d);
System.out.println(res9); // >>> 2
List<String> res10 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res10); // >>> [Norem, Royce, Prickett]
long res11 = jedis.zrank("racer_scores", "Norem");
System.out.println(res11); // >>> 0
long res12 = jedis.zrevrank("racer_scores", "Norem");
System.out.println(res12); // >>> 2
long res13 = jedis.zadd("racer_scores", new HashMap<String,Double>() {{
put("Norem", 0d);
put("Sam-Bodden", 0d);
put("Royce", 0d);
put("Ford", 0d);
put("Prickett", 0d);
put("Castilla", 0d);
}});
System.out.println(res13); // >>> 3
List<String> res14 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res14); // >>> [Castilla, Ford, Norem, Prickett, Royce, Sam-Bodden]
List<String> res15 = jedis.zrangeByLex("racer_scores", "[A", "[L");
System.out.println(res15); // >>> [Castilla, Ford]
long res16 = jedis.zadd("racer_scores", 100d, "Wood");
System.out.println(res16); // >>> 1
long res17 = jedis.zadd("racer_scores", 100d, "Henshaw");
System.out.println(res17); // >>> 1
long res18 = jedis.zadd("racer_scores", 100d, "Henshaw");
System.out.println(res18); // >>> 0
double res19 = jedis.zincrby("racer_scores", 50d, "Wood");
System.out.println(res19); // >>> 150.0
double res20 = jedis.zincrby("racer_scores", 50d, "Henshaw");
System.out.println(res20); // >>> 200.0
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_zadd() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> 1
res2, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> 1
res3, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> 4
}
func ExampleClient_zrange() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> [Ford Sam-Bodden Norem Royce Castilla Prickett]
res5, err := rdb.ZRevRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> [Prickett Castilla Royce Norem Sam-Bodden Ford]
}
func ExampleClient_zrangewithscores() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res6, err := rdb.ZRangeWithScores(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res6)
// >>> [{6 Ford} {8 Sam-Bodden} {10 Norem} {10 Royce} {12 Castilla} {14 Prickett}]
}
func ExampleClient_zrangebyscore() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res7, err := rdb.ZRangeByScore(ctx, "racer_scores",
&redis.ZRangeBy{Min: "-inf", Max: "10"},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res7)
// >>> [Ford Sam-Bodden Norem Royce]
}
func ExampleClient_zremrangebyscore() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res8, err := rdb.ZRem(ctx, "racer_scores", "Castilla").Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> 1
res9, err := rdb.ZRemRangeByScore(ctx, "racer_scores", "-inf", "9").Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> 2
res10, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res10)
// >>> [Norem Royce Prickett]
}
func ExampleClient_zrank() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Prickett", Score: 14},
).Result()
if err != nil {
panic(err)
}
res11, err := rdb.ZRank(ctx, "racer_scores", "Norem").Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> 0
res12, err := rdb.ZRevRank(ctx, "racer_scores", "Norem").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> 2
}
func ExampleClient_zaddlex() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 0},
redis.Z{Member: "Royce", Score: 0},
redis.Z{Member: "Prickett", Score: 0},
).Result()
res13, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 0},
redis.Z{Member: "Sam-Bodden", Score: 0},
redis.Z{Member: "Royce", Score: 0},
redis.Z{Member: "Ford", Score: 0},
redis.Z{Member: "Prickett", Score: 0},
redis.Z{Member: "Castilla", Score: 0},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> 3
res14, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res14)
// >>> [Castilla Ford Norem Prickett Royce Sam-Bodden]
res15, err := rdb.ZRangeByLex(ctx, "racer_scores", &redis.ZRangeBy{
Min: "[A", Max: "[L",
}).Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [Castilla Ford]
}
func ExampleClient_leaderboard() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Wood", Score: 100},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> 1
res17, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Henshaw", Score: 100},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> 1
res18, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Henshaw", Score: 150},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> 0
res19, err := rdb.ZIncrBy(ctx, "racer_scores", 50, "Wood").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> 150
res20, err := rdb.ZIncrBy(ctx, "racer_scores", 50, "Henshaw").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> 200
}
using StackExchange.Redis;
public class SortedSetExample
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.SortedSetAdd("racer_scores", "Norem", 10);
Console.WriteLine(res1); // >>> True
bool res2 = db.SortedSetAdd("racer_scores", "Castilla", 12);
Console.WriteLine(res2); // >>> True
long res3 = db.SortedSetAdd("racer_scores", new[]{
new SortedSetEntry("Sam-Bodden", 8),
new SortedSetEntry("Royce", 10),
new SortedSetEntry("Ford", 6),
new SortedSetEntry("Prickett", 14),
new SortedSetEntry("Castilla", 12)
});
Console.WriteLine(res3); // >>> 4
RedisValue[] res4 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res4)); // >>> Ford, Sam-Bodden, Norem, Royce, Castilla, Prickett
RedisValue[] res5 = db.SortedSetRangeByRank("racer_scores", 0, -1, Order.Descending);
Console.WriteLine(string.Join(", ", res5)); // >>> Prickett, Castilla, Royce, Norem, Sam-Bodden, Ford
SortedSetEntry[] res6 = db.SortedSetRangeByRankWithScores("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res6)); // >>> Ford: 6, Sam-Bodden: 8, Norem: 10, Royce: 10, Castilla: 12, Prickett: 14
RedisValue[] res7 = db.SortedSetRangeByScore("racer_scores", double.NegativeInfinity, 10);
Console.WriteLine(string.Join(", ", res7)); // >>> Ford, Sam-Bodden, Norem, Royce
bool res8 = db.SortedSetRemove("racer_scores", "Castilla");
Console.WriteLine(res8); // >>> True
long res9 = db.SortedSetRemoveRangeByScore("racer_scores", double.NegativeInfinity, 9);
Console.WriteLine(res9); // >>> 2
RedisValue[] res10 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res10)); // >>> Norem, Royce, Prickett
long? res11 = db.SortedSetRank("racer_scores", "Norem");
Console.WriteLine(res11); // >>> 0
long? res12 = db.SortedSetRank("racer_scores", "Norem", Order.Descending);
Console.WriteLine(res12); // >>> 2
long res13 = db.SortedSetAdd("racer_scores", new[] {
new SortedSetEntry("Norem", 0),
new SortedSetEntry("Sam-Bodden", 0),
new SortedSetEntry("Royce", 0),
new SortedSetEntry("Ford", 0),
new SortedSetEntry("Prickett", 0),
new SortedSetEntry("Castilla", 0)
});
Console.WriteLine(res13); // >>> 3
RedisValue[] res14 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res14)); // >>> Castilla, Ford, Norem, Pricket, Royce, Sam-Bodden
RedisValue[] res15 = db.SortedSetRangeByValue("racer_scores", "A", "L", Exclude.None);
Console.WriteLine(string.Join(", ", res15)); // >>> Castilla, Ford
bool res16 = db.SortedSetAdd("racer_scores", "Wood", 100);
Console.WriteLine(res16); // >>> True
bool res17 = db.SortedSetAdd("racer_scores", "Henshaw", 100);
Console.WriteLine(res17); // >>> True
bool res18 = db.SortedSetAdd("racer_scores", "Henshaw", 150);
Console.WriteLine(res18); // >>> False
double res19 = db.SortedSetIncrement("racer_scores", "Wood", 50);
Console.WriteLine(res19); // >>> 150.0
double res20 = db.SortedSetIncrement("racer_scores", "Henshaw", 50);
Console.WriteLine(res20); // >>> 200.0
}
}
As you can see ZADD
is similar to SADD
, but takes one additional argument
(placed before the element to be added) which is the score.
ZADD
is also variadic, so you are free to specify multiple score-value
pairs, even if this is not used in the example above.
With sorted sets it is trivial to return a list of racers sorted by their birth year because actually they are already sorted.
Implementation note: Sorted sets are implemented via a
dual-ported data structure containing both a skip list and a hash table, so
every time we add an element Redis performs an O(log(N)) operation. That's
good, so when we ask for sorted elements, Redis does not have to do any work at
all, it's already sorted. Note that the ZRANGE
order is low to high, while the ZREVRANGE
order is high to low:
> ZRANGE racer_scores 0 -1
1) "Ford"
2) "Sam-Bodden"
3) "Norem"
4) "Royce"
5) "Castilla"
6) "Prickett"
> ZREVRANGE racer_scores 0 -1
1) "Prickett"
2) "Castilla"
3) "Royce"
4) "Norem"
5) "Sam-Bodden"
6) "Ford"
"""
Code samples for Sorted set doc pages:
https://redis.io/docs/latest/develop/data-types/sorted-sets/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.zadd("racer_scores", {"Norem": 10})
print(res1) # >>> 1
res2 = r.zadd("racer_scores", {"Castilla": 12})
print(res2) # >>> 1
res3 = r.zadd(
"racer_scores",
{"Sam-Bodden": 8, "Royce": 10, "Ford": 6, "Prickett": 14, "Castilla": 12},
)
print(res3) # >>> 4
res4 = r.zrange("racer_scores", 0, -1)
print(res4) # >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce', 'Castilla', 'Prickett']
res5 = r.zrevrange("racer_scores", 0, -1)
print(res5) # >>> ['Prickett', 'Castilla', 'Royce', 'Norem', 'Sam-Bodden', 'Ford']
res6 = r.zrange("racer_scores", 0, -1, withscores=True)
print(
res6
)
# >>> [
# ('Ford', 6.0), ('Sam-Bodden', 8.0), ('Norem', 10.0), ('Royce', 10.0),
# ('Castilla', 12.0), ('Prickett', 14.0)
# ]
res7 = r.zrangebyscore("racer_scores", "-inf", 10)
print(res7) # >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce']
res8 = r.zrem("racer_scores", "Castilla")
print(res8) # >>> 1
res9 = r.zremrangebyscore("racer_scores", "-inf", 9)
print(res9) # >>> 2
res10 = r.zrange("racer_scores", 0, -1)
print(res10) # >>> ['Norem', 'Royce', 'Prickett']
res11 = r.zrank("racer_scores", "Norem")
print(res11) # >>> 0
res12 = r.zrevrank("racer_scores", "Norem")
print(res12) # >>> 2
res13 = r.zadd(
"racer_scores",
{
"Norem": 0,
"Sam-Bodden": 0,
"Royce": 0,
"Ford": 0,
"Prickett": 0,
"Castilla": 0,
},
)
print(res13) # >>> 3
res14 = r.zrange("racer_scores", 0, -1)
print(res14) # >>> ['Castilla', 'Ford', 'Norem', 'Prickett', 'Royce', 'Sam-Bodden']
res15 = r.zrangebylex("racer_scores", "[A", "[L")
print(res15) # >>> ['Castilla', 'Ford']
res16 = r.zadd("racer_scores", {"Wood": 100})
print(res16) # >>> 1
res17 = r.zadd("racer_scores", {"Henshaw": 100})
print(res17) # >>> 1
res18 = r.zadd("racer_scores", {"Henshaw": 150})
print(res18) # >>> 0
res19 = r.zincrby("racer_scores", 50, "Wood")
print(res19) # >>> 150.0
res20 = r.zincrby("racer_scores", 50, "Henshaw")
print(res20) # >>> 200.0
import assert from 'assert';
import { createClient } from 'redis';
const client = createClient();
await client.connect();
const res1 = await client.zAdd('racer_scores', { score: 10, value: 'Norem' });
console.log(res1); // >>> 1
const res2 = await client.zAdd('racer_scores', { score: 12, value: 'Castilla' });
console.log(res2); // >>> 1
const res3 = await client.zAdd('racer_scores', [
{ score: 8, value: 'Sam-Bodden' },
{ score: 10, value: 'Royce' },
{ score: 6, value: 'Ford' },
{ score: 14, value: 'Prickett' },
{ score: 12, value: 'Castilla' }
]);
console.log(res3); // >>> 4
const res4 = await client.zRange('racer_scores', 0, -1);
console.log(res4); // >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce', 'Castilla', 'Prickett']
const res6 = await client.zRangeWithScores('racer_scores', 0, -1);
console.log(res6);
// >>> [
// { value: 'Ford', score: 6 }, { value: 'Sam-Bodden', score: 8 },
// { value: 'Norem', score: 10 }, { value: 'Royce', score: 10 },
// { value: 'Castilla', score: 12 }, { value: 'Prickett', score: 14 }
// ]
const res7 = await client.zRangeByScore('racer_scores', '-inf', 10);
console.log(res7); // >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce']
const res8 = await client.zRem('racer_scores', 'Castilla');
console.log(res8); // >>> 1
const res9 = await client.zRemRangeByScore('racer_scores', '-inf', 9);
console.log(res9); // >>> 2
const res10 = await client.zRange('racer_scores', 0, -1);
console.log(res10); // >>> ['Norem', 'Royce', 'Prickett']
const res11 = await client.zRank('racer_scores', 'Norem');
console.log(res11); // >>> 0
const res12 = await client.zRevRank('racer_scores', 'Norem');
console.log(res12); // >>> 2
const res13 = await client.zAdd('racer_scores', [
{ score: 0, value: 'Norem' },
{ score: 0, value: 'Sam-Bodden' },
{ score: 0, value: 'Royce' },
{ score: 0, value: 'Ford' },
{ score: 0, value: 'Prickett' },
{ score: 0, value: 'Castilla' }
]);
console.log(res13); // >>> 3
const res14 = await client.zRange('racer_scores', 0, -1);
console.log(res14); // >>> ['Castilla', 'Ford', 'Norem', 'Prickett', 'Royce', 'Sam-Bodden']
const res15 = await client.zRangeByLex('racer_scores', '[A', '[L');
console.log(res15); // >>> ['Castilla', 'Ford']
const res16 = await client.zAdd('racer_scores', { score: 100, value: 'Wood' });
console.log(res16); // >>> 1
const res17 = await client.zAdd('racer_scores', { score: 100, value: 'Henshaw' });
console.log(res17); // >>> 1
const res18 = await client.zAdd('racer_scores', { score: 150, value: 'Henshaw' }, { nx: true });
console.log(res18); // >>> 0
const res19 = await client.zIncrBy('racer_scores', 50, 'Wood');
console.log(res19); // >>> 150.0
const res20 = await client.zIncrBy('racer_scores', 50, 'Henshaw');
console.log(res20); // >>> 200.0
package io.redis.examples;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.resps.Tuple;
public class SortedSetsExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
long res1 = jedis.zadd("racer_scores", 10d, "Norem");
System.out.println(res1); // >>> 1
long res2 = jedis.zadd("racer_scores", 12d, "Castilla");
System.out.println(res2); // >>> 1
long res3 = jedis.zadd("racer_scores", new HashMap<String,Double>() {{
put("Sam-Bodden", 8d);
put("Royce", 10d);
put("Ford", 6d);
put("Prickett", 14d);
put("Castilla", 12d);
}});
System.out.println(res3); // >>> 4
List<String> res4 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res4); // >>> [Ford, Sam-Bodden, Norem, Royce, Castil, Castilla, Prickett]
List<String> res5 = jedis.zrevrange("racer_scores", 0, -1);
System.out.println(res5); // >>> [Prickett, Castilla, Castil, Royce, Norem, Sam-Bodden, Ford]
List<Tuple> res6 = jedis.zrangeWithScores("racer_scores", 0, -1);
System.out.println(res6); // >>> [[Ford,6.0], [Sam-Bodden,8.0], [Norem,10.0], [Royce,10.0], [Castil,12.0], [Castilla,12.0], [Prickett,14.0]]
List<String> res7 = jedis.zrangeByScore("racer_scores", Double.MIN_VALUE, 10d);
System.out.println(res7); // >>> [Ford, Sam-Bodden, Norem, Royce]
long res8 = jedis.zrem("racer_scores", "Castilla");
System.out.println(res8); // >>> 1
long res9 = jedis.zremrangeByScore("racer_scores", Double.MIN_VALUE, 9d);
System.out.println(res9); // >>> 2
List<String> res10 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res10); // >>> [Norem, Royce, Prickett]
long res11 = jedis.zrank("racer_scores", "Norem");
System.out.println(res11); // >>> 0
long res12 = jedis.zrevrank("racer_scores", "Norem");
System.out.println(res12); // >>> 2
long res13 = jedis.zadd("racer_scores", new HashMap<String,Double>() {{
put("Norem", 0d);
put("Sam-Bodden", 0d);
put("Royce", 0d);
put("Ford", 0d);
put("Prickett", 0d);
put("Castilla", 0d);
}});
System.out.println(res13); // >>> 3
List<String> res14 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res14); // >>> [Castilla, Ford, Norem, Prickett, Royce, Sam-Bodden]
List<String> res15 = jedis.zrangeByLex("racer_scores", "[A", "[L");
System.out.println(res15); // >>> [Castilla, Ford]
long res16 = jedis.zadd("racer_scores", 100d, "Wood");
System.out.println(res16); // >>> 1
long res17 = jedis.zadd("racer_scores", 100d, "Henshaw");
System.out.println(res17); // >>> 1
long res18 = jedis.zadd("racer_scores", 100d, "Henshaw");
System.out.println(res18); // >>> 0
double res19 = jedis.zincrby("racer_scores", 50d, "Wood");
System.out.println(res19); // >>> 150.0
double res20 = jedis.zincrby("racer_scores", 50d, "Henshaw");
System.out.println(res20); // >>> 200.0
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_zadd() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> 1
res2, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> 1
res3, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> 4
}
func ExampleClient_zrange() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> [Ford Sam-Bodden Norem Royce Castilla Prickett]
res5, err := rdb.ZRevRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> [Prickett Castilla Royce Norem Sam-Bodden Ford]
}
func ExampleClient_zrangewithscores() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res6, err := rdb.ZRangeWithScores(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res6)
// >>> [{6 Ford} {8 Sam-Bodden} {10 Norem} {10 Royce} {12 Castilla} {14 Prickett}]
}
func ExampleClient_zrangebyscore() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res7, err := rdb.ZRangeByScore(ctx, "racer_scores",
&redis.ZRangeBy{Min: "-inf", Max: "10"},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res7)
// >>> [Ford Sam-Bodden Norem Royce]
}
func ExampleClient_zremrangebyscore() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res8, err := rdb.ZRem(ctx, "racer_scores", "Castilla").Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> 1
res9, err := rdb.ZRemRangeByScore(ctx, "racer_scores", "-inf", "9").Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> 2
res10, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res10)
// >>> [Norem Royce Prickett]
}
func ExampleClient_zrank() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Prickett", Score: 14},
).Result()
if err != nil {
panic(err)
}
res11, err := rdb.ZRank(ctx, "racer_scores", "Norem").Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> 0
res12, err := rdb.ZRevRank(ctx, "racer_scores", "Norem").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> 2
}
func ExampleClient_zaddlex() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 0},
redis.Z{Member: "Royce", Score: 0},
redis.Z{Member: "Prickett", Score: 0},
).Result()
res13, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 0},
redis.Z{Member: "Sam-Bodden", Score: 0},
redis.Z{Member: "Royce", Score: 0},
redis.Z{Member: "Ford", Score: 0},
redis.Z{Member: "Prickett", Score: 0},
redis.Z{Member: "Castilla", Score: 0},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> 3
res14, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res14)
// >>> [Castilla Ford Norem Prickett Royce Sam-Bodden]
res15, err := rdb.ZRangeByLex(ctx, "racer_scores", &redis.ZRangeBy{
Min: "[A", Max: "[L",
}).Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [Castilla Ford]
}
func ExampleClient_leaderboard() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Wood", Score: 100},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> 1
res17, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Henshaw", Score: 100},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> 1
res18, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Henshaw", Score: 150},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> 0
res19, err := rdb.ZIncrBy(ctx, "racer_scores", 50, "Wood").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> 150
res20, err := rdb.ZIncrBy(ctx, "racer_scores", 50, "Henshaw").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> 200
}
using StackExchange.Redis;
public class SortedSetExample
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.SortedSetAdd("racer_scores", "Norem", 10);
Console.WriteLine(res1); // >>> True
bool res2 = db.SortedSetAdd("racer_scores", "Castilla", 12);
Console.WriteLine(res2); // >>> True
long res3 = db.SortedSetAdd("racer_scores", new[]{
new SortedSetEntry("Sam-Bodden", 8),
new SortedSetEntry("Royce", 10),
new SortedSetEntry("Ford", 6),
new SortedSetEntry("Prickett", 14),
new SortedSetEntry("Castilla", 12)
});
Console.WriteLine(res3); // >>> 4
RedisValue[] res4 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res4)); // >>> Ford, Sam-Bodden, Norem, Royce, Castilla, Prickett
RedisValue[] res5 = db.SortedSetRangeByRank("racer_scores", 0, -1, Order.Descending);
Console.WriteLine(string.Join(", ", res5)); // >>> Prickett, Castilla, Royce, Norem, Sam-Bodden, Ford
SortedSetEntry[] res6 = db.SortedSetRangeByRankWithScores("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res6)); // >>> Ford: 6, Sam-Bodden: 8, Norem: 10, Royce: 10, Castilla: 12, Prickett: 14
RedisValue[] res7 = db.SortedSetRangeByScore("racer_scores", double.NegativeInfinity, 10);
Console.WriteLine(string.Join(", ", res7)); // >>> Ford, Sam-Bodden, Norem, Royce
bool res8 = db.SortedSetRemove("racer_scores", "Castilla");
Console.WriteLine(res8); // >>> True
long res9 = db.SortedSetRemoveRangeByScore("racer_scores", double.NegativeInfinity, 9);
Console.WriteLine(res9); // >>> 2
RedisValue[] res10 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res10)); // >>> Norem, Royce, Prickett
long? res11 = db.SortedSetRank("racer_scores", "Norem");
Console.WriteLine(res11); // >>> 0
long? res12 = db.SortedSetRank("racer_scores", "Norem", Order.Descending);
Console.WriteLine(res12); // >>> 2
long res13 = db.SortedSetAdd("racer_scores", new[] {
new SortedSetEntry("Norem", 0),
new SortedSetEntry("Sam-Bodden", 0),
new SortedSetEntry("Royce", 0),
new SortedSetEntry("Ford", 0),
new SortedSetEntry("Prickett", 0),
new SortedSetEntry("Castilla", 0)
});
Console.WriteLine(res13); // >>> 3
RedisValue[] res14 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res14)); // >>> Castilla, Ford, Norem, Pricket, Royce, Sam-Bodden
RedisValue[] res15 = db.SortedSetRangeByValue("racer_scores", "A", "L", Exclude.None);
Console.WriteLine(string.Join(", ", res15)); // >>> Castilla, Ford
bool res16 = db.SortedSetAdd("racer_scores", "Wood", 100);
Console.WriteLine(res16); // >>> True
bool res17 = db.SortedSetAdd("racer_scores", "Henshaw", 100);
Console.WriteLine(res17); // >>> True
bool res18 = db.SortedSetAdd("racer_scores", "Henshaw", 150);
Console.WriteLine(res18); // >>> False
double res19 = db.SortedSetIncrement("racer_scores", "Wood", 50);
Console.WriteLine(res19); // >>> 150.0
double res20 = db.SortedSetIncrement("racer_scores", "Henshaw", 50);
Console.WriteLine(res20); // >>> 200.0
}
}
Note: 0 and -1 means from element index 0 to the last element (-1 works
here just as it does in the case of the LRANGE
command).
It is possible to return scores as well, using the WITHSCORES
argument:
> ZRANGE racer_scores 0 -1 withscores
1) "Ford"
2) "6"
3) "Sam-Bodden"
4) "8"
5) "Norem"
6) "10"
7) "Royce"
8) "10"
9) "Castilla"
10) "12"
11) "Prickett"
12) "14"
"""
Code samples for Sorted set doc pages:
https://redis.io/docs/latest/develop/data-types/sorted-sets/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.zadd("racer_scores", {"Norem": 10})
print(res1) # >>> 1
res2 = r.zadd("racer_scores", {"Castilla": 12})
print(res2) # >>> 1
res3 = r.zadd(
"racer_scores",
{"Sam-Bodden": 8, "Royce": 10, "Ford": 6, "Prickett": 14, "Castilla": 12},
)
print(res3) # >>> 4
res4 = r.zrange("racer_scores", 0, -1)
print(res4) # >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce', 'Castilla', 'Prickett']
res5 = r.zrevrange("racer_scores", 0, -1)
print(res5) # >>> ['Prickett', 'Castilla', 'Royce', 'Norem', 'Sam-Bodden', 'Ford']
res6 = r.zrange("racer_scores", 0, -1, withscores=True)
print(
res6
)
# >>> [
# ('Ford', 6.0), ('Sam-Bodden', 8.0), ('Norem', 10.0), ('Royce', 10.0),
# ('Castilla', 12.0), ('Prickett', 14.0)
# ]
res7 = r.zrangebyscore("racer_scores", "-inf", 10)
print(res7) # >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce']
res8 = r.zrem("racer_scores", "Castilla")
print(res8) # >>> 1
res9 = r.zremrangebyscore("racer_scores", "-inf", 9)
print(res9) # >>> 2
res10 = r.zrange("racer_scores", 0, -1)
print(res10) # >>> ['Norem', 'Royce', 'Prickett']
res11 = r.zrank("racer_scores", "Norem")
print(res11) # >>> 0
res12 = r.zrevrank("racer_scores", "Norem")
print(res12) # >>> 2
res13 = r.zadd(
"racer_scores",
{
"Norem": 0,
"Sam-Bodden": 0,
"Royce": 0,
"Ford": 0,
"Prickett": 0,
"Castilla": 0,
},
)
print(res13) # >>> 3
res14 = r.zrange("racer_scores", 0, -1)
print(res14) # >>> ['Castilla', 'Ford', 'Norem', 'Prickett', 'Royce', 'Sam-Bodden']
res15 = r.zrangebylex("racer_scores", "[A", "[L")
print(res15) # >>> ['Castilla', 'Ford']
res16 = r.zadd("racer_scores", {"Wood": 100})
print(res16) # >>> 1
res17 = r.zadd("racer_scores", {"Henshaw": 100})
print(res17) # >>> 1
res18 = r.zadd("racer_scores", {"Henshaw": 150})
print(res18) # >>> 0
res19 = r.zincrby("racer_scores", 50, "Wood")
print(res19) # >>> 150.0
res20 = r.zincrby("racer_scores", 50, "Henshaw")
print(res20) # >>> 200.0
import assert from 'assert';
import { createClient } from 'redis';
const client = createClient();
await client.connect();
const res1 = await client.zAdd('racer_scores', { score: 10, value: 'Norem' });
console.log(res1); // >>> 1
const res2 = await client.zAdd('racer_scores', { score: 12, value: 'Castilla' });
console.log(res2); // >>> 1
const res3 = await client.zAdd('racer_scores', [
{ score: 8, value: 'Sam-Bodden' },
{ score: 10, value: 'Royce' },
{ score: 6, value: 'Ford' },
{ score: 14, value: 'Prickett' },
{ score: 12, value: 'Castilla' }
]);
console.log(res3); // >>> 4
const res4 = await client.zRange('racer_scores', 0, -1);
console.log(res4); // >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce', 'Castilla', 'Prickett']
const res6 = await client.zRangeWithScores('racer_scores', 0, -1);
console.log(res6);
// >>> [
// { value: 'Ford', score: 6 }, { value: 'Sam-Bodden', score: 8 },
// { value: 'Norem', score: 10 }, { value: 'Royce', score: 10 },
// { value: 'Castilla', score: 12 }, { value: 'Prickett', score: 14 }
// ]
const res7 = await client.zRangeByScore('racer_scores', '-inf', 10);
console.log(res7); // >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce']
const res8 = await client.zRem('racer_scores', 'Castilla');
console.log(res8); // >>> 1
const res9 = await client.zRemRangeByScore('racer_scores', '-inf', 9);
console.log(res9); // >>> 2
const res10 = await client.zRange('racer_scores', 0, -1);
console.log(res10); // >>> ['Norem', 'Royce', 'Prickett']
const res11 = await client.zRank('racer_scores', 'Norem');
console.log(res11); // >>> 0
const res12 = await client.zRevRank('racer_scores', 'Norem');
console.log(res12); // >>> 2
const res13 = await client.zAdd('racer_scores', [
{ score: 0, value: 'Norem' },
{ score: 0, value: 'Sam-Bodden' },
{ score: 0, value: 'Royce' },
{ score: 0, value: 'Ford' },
{ score: 0, value: 'Prickett' },
{ score: 0, value: 'Castilla' }
]);
console.log(res13); // >>> 3
const res14 = await client.zRange('racer_scores', 0, -1);
console.log(res14); // >>> ['Castilla', 'Ford', 'Norem', 'Prickett', 'Royce', 'Sam-Bodden']
const res15 = await client.zRangeByLex('racer_scores', '[A', '[L');
console.log(res15); // >>> ['Castilla', 'Ford']
const res16 = await client.zAdd('racer_scores', { score: 100, value: 'Wood' });
console.log(res16); // >>> 1
const res17 = await client.zAdd('racer_scores', { score: 100, value: 'Henshaw' });
console.log(res17); // >>> 1
const res18 = await client.zAdd('racer_scores', { score: 150, value: 'Henshaw' }, { nx: true });
console.log(res18); // >>> 0
const res19 = await client.zIncrBy('racer_scores', 50, 'Wood');
console.log(res19); // >>> 150.0
const res20 = await client.zIncrBy('racer_scores', 50, 'Henshaw');
console.log(res20); // >>> 200.0
package io.redis.examples;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.resps.Tuple;
public class SortedSetsExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
long res1 = jedis.zadd("racer_scores", 10d, "Norem");
System.out.println(res1); // >>> 1
long res2 = jedis.zadd("racer_scores", 12d, "Castilla");
System.out.println(res2); // >>> 1
long res3 = jedis.zadd("racer_scores", new HashMap<String,Double>() {{
put("Sam-Bodden", 8d);
put("Royce", 10d);
put("Ford", 6d);
put("Prickett", 14d);
put("Castilla", 12d);
}});
System.out.println(res3); // >>> 4
List<String> res4 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res4); // >>> [Ford, Sam-Bodden, Norem, Royce, Castil, Castilla, Prickett]
List<String> res5 = jedis.zrevrange("racer_scores", 0, -1);
System.out.println(res5); // >>> [Prickett, Castilla, Castil, Royce, Norem, Sam-Bodden, Ford]
List<Tuple> res6 = jedis.zrangeWithScores("racer_scores", 0, -1);
System.out.println(res6); // >>> [[Ford,6.0], [Sam-Bodden,8.0], [Norem,10.0], [Royce,10.0], [Castil,12.0], [Castilla,12.0], [Prickett,14.0]]
List<String> res7 = jedis.zrangeByScore("racer_scores", Double.MIN_VALUE, 10d);
System.out.println(res7); // >>> [Ford, Sam-Bodden, Norem, Royce]
long res8 = jedis.zrem("racer_scores", "Castilla");
System.out.println(res8); // >>> 1
long res9 = jedis.zremrangeByScore("racer_scores", Double.MIN_VALUE, 9d);
System.out.println(res9); // >>> 2
List<String> res10 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res10); // >>> [Norem, Royce, Prickett]
long res11 = jedis.zrank("racer_scores", "Norem");
System.out.println(res11); // >>> 0
long res12 = jedis.zrevrank("racer_scores", "Norem");
System.out.println(res12); // >>> 2
long res13 = jedis.zadd("racer_scores", new HashMap<String,Double>() {{
put("Norem", 0d);
put("Sam-Bodden", 0d);
put("Royce", 0d);
put("Ford", 0d);
put("Prickett", 0d);
put("Castilla", 0d);
}});
System.out.println(res13); // >>> 3
List<String> res14 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res14); // >>> [Castilla, Ford, Norem, Prickett, Royce, Sam-Bodden]
List<String> res15 = jedis.zrangeByLex("racer_scores", "[A", "[L");
System.out.println(res15); // >>> [Castilla, Ford]
long res16 = jedis.zadd("racer_scores", 100d, "Wood");
System.out.println(res16); // >>> 1
long res17 = jedis.zadd("racer_scores", 100d, "Henshaw");
System.out.println(res17); // >>> 1
long res18 = jedis.zadd("racer_scores", 100d, "Henshaw");
System.out.println(res18); // >>> 0
double res19 = jedis.zincrby("racer_scores", 50d, "Wood");
System.out.println(res19); // >>> 150.0
double res20 = jedis.zincrby("racer_scores", 50d, "Henshaw");
System.out.println(res20); // >>> 200.0
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_zadd() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> 1
res2, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> 1
res3, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> 4
}
func ExampleClient_zrange() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> [Ford Sam-Bodden Norem Royce Castilla Prickett]
res5, err := rdb.ZRevRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> [Prickett Castilla Royce Norem Sam-Bodden Ford]
}
func ExampleClient_zrangewithscores() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res6, err := rdb.ZRangeWithScores(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res6)
// >>> [{6 Ford} {8 Sam-Bodden} {10 Norem} {10 Royce} {12 Castilla} {14 Prickett}]
}
func ExampleClient_zrangebyscore() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res7, err := rdb.ZRangeByScore(ctx, "racer_scores",
&redis.ZRangeBy{Min: "-inf", Max: "10"},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res7)
// >>> [Ford Sam-Bodden Norem Royce]
}
func ExampleClient_zremrangebyscore() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res8, err := rdb.ZRem(ctx, "racer_scores", "Castilla").Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> 1
res9, err := rdb.ZRemRangeByScore(ctx, "racer_scores", "-inf", "9").Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> 2
res10, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res10)
// >>> [Norem Royce Prickett]
}
func ExampleClient_zrank() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Prickett", Score: 14},
).Result()
if err != nil {
panic(err)
}
res11, err := rdb.ZRank(ctx, "racer_scores", "Norem").Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> 0
res12, err := rdb.ZRevRank(ctx, "racer_scores", "Norem").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> 2
}
func ExampleClient_zaddlex() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 0},
redis.Z{Member: "Royce", Score: 0},
redis.Z{Member: "Prickett", Score: 0},
).Result()
res13, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 0},
redis.Z{Member: "Sam-Bodden", Score: 0},
redis.Z{Member: "Royce", Score: 0},
redis.Z{Member: "Ford", Score: 0},
redis.Z{Member: "Prickett", Score: 0},
redis.Z{Member: "Castilla", Score: 0},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> 3
res14, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res14)
// >>> [Castilla Ford Norem Prickett Royce Sam-Bodden]
res15, err := rdb.ZRangeByLex(ctx, "racer_scores", &redis.ZRangeBy{
Min: "[A", Max: "[L",
}).Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [Castilla Ford]
}
func ExampleClient_leaderboard() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Wood", Score: 100},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> 1
res17, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Henshaw", Score: 100},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> 1
res18, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Henshaw", Score: 150},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> 0
res19, err := rdb.ZIncrBy(ctx, "racer_scores", 50, "Wood").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> 150
res20, err := rdb.ZIncrBy(ctx, "racer_scores", 50, "Henshaw").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> 200
}
using StackExchange.Redis;
public class SortedSetExample
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.SortedSetAdd("racer_scores", "Norem", 10);
Console.WriteLine(res1); // >>> True
bool res2 = db.SortedSetAdd("racer_scores", "Castilla", 12);
Console.WriteLine(res2); // >>> True
long res3 = db.SortedSetAdd("racer_scores", new[]{
new SortedSetEntry("Sam-Bodden", 8),
new SortedSetEntry("Royce", 10),
new SortedSetEntry("Ford", 6),
new SortedSetEntry("Prickett", 14),
new SortedSetEntry("Castilla", 12)
});
Console.WriteLine(res3); // >>> 4
RedisValue[] res4 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res4)); // >>> Ford, Sam-Bodden, Norem, Royce, Castilla, Prickett
RedisValue[] res5 = db.SortedSetRangeByRank("racer_scores", 0, -1, Order.Descending);
Console.WriteLine(string.Join(", ", res5)); // >>> Prickett, Castilla, Royce, Norem, Sam-Bodden, Ford
SortedSetEntry[] res6 = db.SortedSetRangeByRankWithScores("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res6)); // >>> Ford: 6, Sam-Bodden: 8, Norem: 10, Royce: 10, Castilla: 12, Prickett: 14
RedisValue[] res7 = db.SortedSetRangeByScore("racer_scores", double.NegativeInfinity, 10);
Console.WriteLine(string.Join(", ", res7)); // >>> Ford, Sam-Bodden, Norem, Royce
bool res8 = db.SortedSetRemove("racer_scores", "Castilla");
Console.WriteLine(res8); // >>> True
long res9 = db.SortedSetRemoveRangeByScore("racer_scores", double.NegativeInfinity, 9);
Console.WriteLine(res9); // >>> 2
RedisValue[] res10 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res10)); // >>> Norem, Royce, Prickett
long? res11 = db.SortedSetRank("racer_scores", "Norem");
Console.WriteLine(res11); // >>> 0
long? res12 = db.SortedSetRank("racer_scores", "Norem", Order.Descending);
Console.WriteLine(res12); // >>> 2
long res13 = db.SortedSetAdd("racer_scores", new[] {
new SortedSetEntry("Norem", 0),
new SortedSetEntry("Sam-Bodden", 0),
new SortedSetEntry("Royce", 0),
new SortedSetEntry("Ford", 0),
new SortedSetEntry("Prickett", 0),
new SortedSetEntry("Castilla", 0)
});
Console.WriteLine(res13); // >>> 3
RedisValue[] res14 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res14)); // >>> Castilla, Ford, Norem, Pricket, Royce, Sam-Bodden
RedisValue[] res15 = db.SortedSetRangeByValue("racer_scores", "A", "L", Exclude.None);
Console.WriteLine(string.Join(", ", res15)); // >>> Castilla, Ford
bool res16 = db.SortedSetAdd("racer_scores", "Wood", 100);
Console.WriteLine(res16); // >>> True
bool res17 = db.SortedSetAdd("racer_scores", "Henshaw", 100);
Console.WriteLine(res17); // >>> True
bool res18 = db.SortedSetAdd("racer_scores", "Henshaw", 150);
Console.WriteLine(res18); // >>> False
double res19 = db.SortedSetIncrement("racer_scores", "Wood", 50);
Console.WriteLine(res19); // >>> 150.0
double res20 = db.SortedSetIncrement("racer_scores", "Henshaw", 50);
Console.WriteLine(res20); // >>> 200.0
}
}
Operating on ranges
Sorted sets are more powerful than this. They can operate on ranges.
Let's get all the racers with 10 or fewer points. We
use the ZRANGEBYSCORE
command to do it:
> ZRANGEBYSCORE racer_scores -inf 10
1) "Ford"
2) "Sam-Bodden"
3) "Norem"
4) "Royce"
"""
Code samples for Sorted set doc pages:
https://redis.io/docs/latest/develop/data-types/sorted-sets/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.zadd("racer_scores", {"Norem": 10})
print(res1) # >>> 1
res2 = r.zadd("racer_scores", {"Castilla": 12})
print(res2) # >>> 1
res3 = r.zadd(
"racer_scores",
{"Sam-Bodden": 8, "Royce": 10, "Ford": 6, "Prickett": 14, "Castilla": 12},
)
print(res3) # >>> 4
res4 = r.zrange("racer_scores", 0, -1)
print(res4) # >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce', 'Castilla', 'Prickett']
res5 = r.zrevrange("racer_scores", 0, -1)
print(res5) # >>> ['Prickett', 'Castilla', 'Royce', 'Norem', 'Sam-Bodden', 'Ford']
res6 = r.zrange("racer_scores", 0, -1, withscores=True)
print(
res6
)
# >>> [
# ('Ford', 6.0), ('Sam-Bodden', 8.0), ('Norem', 10.0), ('Royce', 10.0),
# ('Castilla', 12.0), ('Prickett', 14.0)
# ]
res7 = r.zrangebyscore("racer_scores", "-inf", 10)
print(res7) # >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce']
res8 = r.zrem("racer_scores", "Castilla")
print(res8) # >>> 1
res9 = r.zremrangebyscore("racer_scores", "-inf", 9)
print(res9) # >>> 2
res10 = r.zrange("racer_scores", 0, -1)
print(res10) # >>> ['Norem', 'Royce', 'Prickett']
res11 = r.zrank("racer_scores", "Norem")
print(res11) # >>> 0
res12 = r.zrevrank("racer_scores", "Norem")
print(res12) # >>> 2
res13 = r.zadd(
"racer_scores",
{
"Norem": 0,
"Sam-Bodden": 0,
"Royce": 0,
"Ford": 0,
"Prickett": 0,
"Castilla": 0,
},
)
print(res13) # >>> 3
res14 = r.zrange("racer_scores", 0, -1)
print(res14) # >>> ['Castilla', 'Ford', 'Norem', 'Prickett', 'Royce', 'Sam-Bodden']
res15 = r.zrangebylex("racer_scores", "[A", "[L")
print(res15) # >>> ['Castilla', 'Ford']
res16 = r.zadd("racer_scores", {"Wood": 100})
print(res16) # >>> 1
res17 = r.zadd("racer_scores", {"Henshaw": 100})
print(res17) # >>> 1
res18 = r.zadd("racer_scores", {"Henshaw": 150})
print(res18) # >>> 0
res19 = r.zincrby("racer_scores", 50, "Wood")
print(res19) # >>> 150.0
res20 = r.zincrby("racer_scores", 50, "Henshaw")
print(res20) # >>> 200.0
import assert from 'assert';
import { createClient } from 'redis';
const client = createClient();
await client.connect();
const res1 = await client.zAdd('racer_scores', { score: 10, value: 'Norem' });
console.log(res1); // >>> 1
const res2 = await client.zAdd('racer_scores', { score: 12, value: 'Castilla' });
console.log(res2); // >>> 1
const res3 = await client.zAdd('racer_scores', [
{ score: 8, value: 'Sam-Bodden' },
{ score: 10, value: 'Royce' },
{ score: 6, value: 'Ford' },
{ score: 14, value: 'Prickett' },
{ score: 12, value: 'Castilla' }
]);
console.log(res3); // >>> 4
const res4 = await client.zRange('racer_scores', 0, -1);
console.log(res4); // >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce', 'Castilla', 'Prickett']
const res6 = await client.zRangeWithScores('racer_scores', 0, -1);
console.log(res6);
// >>> [
// { value: 'Ford', score: 6 }, { value: 'Sam-Bodden', score: 8 },
// { value: 'Norem', score: 10 }, { value: 'Royce', score: 10 },
// { value: 'Castilla', score: 12 }, { value: 'Prickett', score: 14 }
// ]
const res7 = await client.zRangeByScore('racer_scores', '-inf', 10);
console.log(res7); // >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce']
const res8 = await client.zRem('racer_scores', 'Castilla');
console.log(res8); // >>> 1
const res9 = await client.zRemRangeByScore('racer_scores', '-inf', 9);
console.log(res9); // >>> 2
const res10 = await client.zRange('racer_scores', 0, -1);
console.log(res10); // >>> ['Norem', 'Royce', 'Prickett']
const res11 = await client.zRank('racer_scores', 'Norem');
console.log(res11); // >>> 0
const res12 = await client.zRevRank('racer_scores', 'Norem');
console.log(res12); // >>> 2
const res13 = await client.zAdd('racer_scores', [
{ score: 0, value: 'Norem' },
{ score: 0, value: 'Sam-Bodden' },
{ score: 0, value: 'Royce' },
{ score: 0, value: 'Ford' },
{ score: 0, value: 'Prickett' },
{ score: 0, value: 'Castilla' }
]);
console.log(res13); // >>> 3
const res14 = await client.zRange('racer_scores', 0, -1);
console.log(res14); // >>> ['Castilla', 'Ford', 'Norem', 'Prickett', 'Royce', 'Sam-Bodden']
const res15 = await client.zRangeByLex('racer_scores', '[A', '[L');
console.log(res15); // >>> ['Castilla', 'Ford']
const res16 = await client.zAdd('racer_scores', { score: 100, value: 'Wood' });
console.log(res16); // >>> 1
const res17 = await client.zAdd('racer_scores', { score: 100, value: 'Henshaw' });
console.log(res17); // >>> 1
const res18 = await client.zAdd('racer_scores', { score: 150, value: 'Henshaw' }, { nx: true });
console.log(res18); // >>> 0
const res19 = await client.zIncrBy('racer_scores', 50, 'Wood');
console.log(res19); // >>> 150.0
const res20 = await client.zIncrBy('racer_scores', 50, 'Henshaw');
console.log(res20); // >>> 200.0
package io.redis.examples;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.resps.Tuple;
public class SortedSetsExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
long res1 = jedis.zadd("racer_scores", 10d, "Norem");
System.out.println(res1); // >>> 1
long res2 = jedis.zadd("racer_scores", 12d, "Castilla");
System.out.println(res2); // >>> 1
long res3 = jedis.zadd("racer_scores", new HashMap<String,Double>() {{
put("Sam-Bodden", 8d);
put("Royce", 10d);
put("Ford", 6d);
put("Prickett", 14d);
put("Castilla", 12d);
}});
System.out.println(res3); // >>> 4
List<String> res4 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res4); // >>> [Ford, Sam-Bodden, Norem, Royce, Castil, Castilla, Prickett]
List<String> res5 = jedis.zrevrange("racer_scores", 0, -1);
System.out.println(res5); // >>> [Prickett, Castilla, Castil, Royce, Norem, Sam-Bodden, Ford]
List<Tuple> res6 = jedis.zrangeWithScores("racer_scores", 0, -1);
System.out.println(res6); // >>> [[Ford,6.0], [Sam-Bodden,8.0], [Norem,10.0], [Royce,10.0], [Castil,12.0], [Castilla,12.0], [Prickett,14.0]]
List<String> res7 = jedis.zrangeByScore("racer_scores", Double.MIN_VALUE, 10d);
System.out.println(res7); // >>> [Ford, Sam-Bodden, Norem, Royce]
long res8 = jedis.zrem("racer_scores", "Castilla");
System.out.println(res8); // >>> 1
long res9 = jedis.zremrangeByScore("racer_scores", Double.MIN_VALUE, 9d);
System.out.println(res9); // >>> 2
List<String> res10 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res10); // >>> [Norem, Royce, Prickett]
long res11 = jedis.zrank("racer_scores", "Norem");
System.out.println(res11); // >>> 0
long res12 = jedis.zrevrank("racer_scores", "Norem");
System.out.println(res12); // >>> 2
long res13 = jedis.zadd("racer_scores", new HashMap<String,Double>() {{
put("Norem", 0d);
put("Sam-Bodden", 0d);
put("Royce", 0d);
put("Ford", 0d);
put("Prickett", 0d);
put("Castilla", 0d);
}});
System.out.println(res13); // >>> 3
List<String> res14 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res14); // >>> [Castilla, Ford, Norem, Prickett, Royce, Sam-Bodden]
List<String> res15 = jedis.zrangeByLex("racer_scores", "[A", "[L");
System.out.println(res15); // >>> [Castilla, Ford]
long res16 = jedis.zadd("racer_scores", 100d, "Wood");
System.out.println(res16); // >>> 1
long res17 = jedis.zadd("racer_scores", 100d, "Henshaw");
System.out.println(res17); // >>> 1
long res18 = jedis.zadd("racer_scores", 100d, "Henshaw");
System.out.println(res18); // >>> 0
double res19 = jedis.zincrby("racer_scores", 50d, "Wood");
System.out.println(res19); // >>> 150.0
double res20 = jedis.zincrby("racer_scores", 50d, "Henshaw");
System.out.println(res20); // >>> 200.0
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_zadd() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> 1
res2, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> 1
res3, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> 4
}
func ExampleClient_zrange() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> [Ford Sam-Bodden Norem Royce Castilla Prickett]
res5, err := rdb.ZRevRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> [Prickett Castilla Royce Norem Sam-Bodden Ford]
}
func ExampleClient_zrangewithscores() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res6, err := rdb.ZRangeWithScores(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res6)
// >>> [{6 Ford} {8 Sam-Bodden} {10 Norem} {10 Royce} {12 Castilla} {14 Prickett}]
}
func ExampleClient_zrangebyscore() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res7, err := rdb.ZRangeByScore(ctx, "racer_scores",
&redis.ZRangeBy{Min: "-inf", Max: "10"},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res7)
// >>> [Ford Sam-Bodden Norem Royce]
}
func ExampleClient_zremrangebyscore() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res8, err := rdb.ZRem(ctx, "racer_scores", "Castilla").Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> 1
res9, err := rdb.ZRemRangeByScore(ctx, "racer_scores", "-inf", "9").Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> 2
res10, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res10)
// >>> [Norem Royce Prickett]
}
func ExampleClient_zrank() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Prickett", Score: 14},
).Result()
if err != nil {
panic(err)
}
res11, err := rdb.ZRank(ctx, "racer_scores", "Norem").Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> 0
res12, err := rdb.ZRevRank(ctx, "racer_scores", "Norem").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> 2
}
func ExampleClient_zaddlex() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 0},
redis.Z{Member: "Royce", Score: 0},
redis.Z{Member: "Prickett", Score: 0},
).Result()
res13, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 0},
redis.Z{Member: "Sam-Bodden", Score: 0},
redis.Z{Member: "Royce", Score: 0},
redis.Z{Member: "Ford", Score: 0},
redis.Z{Member: "Prickett", Score: 0},
redis.Z{Member: "Castilla", Score: 0},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> 3
res14, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res14)
// >>> [Castilla Ford Norem Prickett Royce Sam-Bodden]
res15, err := rdb.ZRangeByLex(ctx, "racer_scores", &redis.ZRangeBy{
Min: "[A", Max: "[L",
}).Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [Castilla Ford]
}
func ExampleClient_leaderboard() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Wood", Score: 100},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> 1
res17, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Henshaw", Score: 100},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> 1
res18, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Henshaw", Score: 150},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> 0
res19, err := rdb.ZIncrBy(ctx, "racer_scores", 50, "Wood").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> 150
res20, err := rdb.ZIncrBy(ctx, "racer_scores", 50, "Henshaw").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> 200
}
using StackExchange.Redis;
public class SortedSetExample
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.SortedSetAdd("racer_scores", "Norem", 10);
Console.WriteLine(res1); // >>> True
bool res2 = db.SortedSetAdd("racer_scores", "Castilla", 12);
Console.WriteLine(res2); // >>> True
long res3 = db.SortedSetAdd("racer_scores", new[]{
new SortedSetEntry("Sam-Bodden", 8),
new SortedSetEntry("Royce", 10),
new SortedSetEntry("Ford", 6),
new SortedSetEntry("Prickett", 14),
new SortedSetEntry("Castilla", 12)
});
Console.WriteLine(res3); // >>> 4
RedisValue[] res4 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res4)); // >>> Ford, Sam-Bodden, Norem, Royce, Castilla, Prickett
RedisValue[] res5 = db.SortedSetRangeByRank("racer_scores", 0, -1, Order.Descending);
Console.WriteLine(string.Join(", ", res5)); // >>> Prickett, Castilla, Royce, Norem, Sam-Bodden, Ford
SortedSetEntry[] res6 = db.SortedSetRangeByRankWithScores("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res6)); // >>> Ford: 6, Sam-Bodden: 8, Norem: 10, Royce: 10, Castilla: 12, Prickett: 14
RedisValue[] res7 = db.SortedSetRangeByScore("racer_scores", double.NegativeInfinity, 10);
Console.WriteLine(string.Join(", ", res7)); // >>> Ford, Sam-Bodden, Norem, Royce
bool res8 = db.SortedSetRemove("racer_scores", "Castilla");
Console.WriteLine(res8); // >>> True
long res9 = db.SortedSetRemoveRangeByScore("racer_scores", double.NegativeInfinity, 9);
Console.WriteLine(res9); // >>> 2
RedisValue[] res10 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res10)); // >>> Norem, Royce, Prickett
long? res11 = db.SortedSetRank("racer_scores", "Norem");
Console.WriteLine(res11); // >>> 0
long? res12 = db.SortedSetRank("racer_scores", "Norem", Order.Descending);
Console.WriteLine(res12); // >>> 2
long res13 = db.SortedSetAdd("racer_scores", new[] {
new SortedSetEntry("Norem", 0),
new SortedSetEntry("Sam-Bodden", 0),
new SortedSetEntry("Royce", 0),
new SortedSetEntry("Ford", 0),
new SortedSetEntry("Prickett", 0),
new SortedSetEntry("Castilla", 0)
});
Console.WriteLine(res13); // >>> 3
RedisValue[] res14 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res14)); // >>> Castilla, Ford, Norem, Pricket, Royce, Sam-Bodden
RedisValue[] res15 = db.SortedSetRangeByValue("racer_scores", "A", "L", Exclude.None);
Console.WriteLine(string.Join(", ", res15)); // >>> Castilla, Ford
bool res16 = db.SortedSetAdd("racer_scores", "Wood", 100);
Console.WriteLine(res16); // >>> True
bool res17 = db.SortedSetAdd("racer_scores", "Henshaw", 100);
Console.WriteLine(res17); // >>> True
bool res18 = db.SortedSetAdd("racer_scores", "Henshaw", 150);
Console.WriteLine(res18); // >>> False
double res19 = db.SortedSetIncrement("racer_scores", "Wood", 50);
Console.WriteLine(res19); // >>> 150.0
double res20 = db.SortedSetIncrement("racer_scores", "Henshaw", 50);
Console.WriteLine(res20); // >>> 200.0
}
}
We asked Redis to return all the elements with a score between negative infinity and 10 (both extremes are included).
To remove an element we'd simply call ZREM
with the racer's name.
It's also possible to remove ranges of elements. Let's remove racer Castilla along with all
the racers with strictly fewer than 10 points:
> ZREM racer_scores "Castilla"
(integer) 1
> ZREMRANGEBYSCORE racer_scores -inf 9
(integer) 2
> ZRANGE racer_scores 0 -1
1) "Norem"
2) "Royce"
3) "Prickett"
"""
Code samples for Sorted set doc pages:
https://redis.io/docs/latest/develop/data-types/sorted-sets/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.zadd("racer_scores", {"Norem": 10})
print(res1) # >>> 1
res2 = r.zadd("racer_scores", {"Castilla": 12})
print(res2) # >>> 1
res3 = r.zadd(
"racer_scores",
{"Sam-Bodden": 8, "Royce": 10, "Ford": 6, "Prickett": 14, "Castilla": 12},
)
print(res3) # >>> 4
res4 = r.zrange("racer_scores", 0, -1)
print(res4) # >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce', 'Castilla', 'Prickett']
res5 = r.zrevrange("racer_scores", 0, -1)
print(res5) # >>> ['Prickett', 'Castilla', 'Royce', 'Norem', 'Sam-Bodden', 'Ford']
res6 = r.zrange("racer_scores", 0, -1, withscores=True)
print(
res6
)
# >>> [
# ('Ford', 6.0), ('Sam-Bodden', 8.0), ('Norem', 10.0), ('Royce', 10.0),
# ('Castilla', 12.0), ('Prickett', 14.0)
# ]
res7 = r.zrangebyscore("racer_scores", "-inf", 10)
print(res7) # >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce']
res8 = r.zrem("racer_scores", "Castilla")
print(res8) # >>> 1
res9 = r.zremrangebyscore("racer_scores", "-inf", 9)
print(res9) # >>> 2
res10 = r.zrange("racer_scores", 0, -1)
print(res10) # >>> ['Norem', 'Royce', 'Prickett']
res11 = r.zrank("racer_scores", "Norem")
print(res11) # >>> 0
res12 = r.zrevrank("racer_scores", "Norem")
print(res12) # >>> 2
res13 = r.zadd(
"racer_scores",
{
"Norem": 0,
"Sam-Bodden": 0,
"Royce": 0,
"Ford": 0,
"Prickett": 0,
"Castilla": 0,
},
)
print(res13) # >>> 3
res14 = r.zrange("racer_scores", 0, -1)
print(res14) # >>> ['Castilla', 'Ford', 'Norem', 'Prickett', 'Royce', 'Sam-Bodden']
res15 = r.zrangebylex("racer_scores", "[A", "[L")
print(res15) # >>> ['Castilla', 'Ford']
res16 = r.zadd("racer_scores", {"Wood": 100})
print(res16) # >>> 1
res17 = r.zadd("racer_scores", {"Henshaw": 100})
print(res17) # >>> 1
res18 = r.zadd("racer_scores", {"Henshaw": 150})
print(res18) # >>> 0
res19 = r.zincrby("racer_scores", 50, "Wood")
print(res19) # >>> 150.0
res20 = r.zincrby("racer_scores", 50, "Henshaw")
print(res20) # >>> 200.0
import assert from 'assert';
import { createClient } from 'redis';
const client = createClient();
await client.connect();
const res1 = await client.zAdd('racer_scores', { score: 10, value: 'Norem' });
console.log(res1); // >>> 1
const res2 = await client.zAdd('racer_scores', { score: 12, value: 'Castilla' });
console.log(res2); // >>> 1
const res3 = await client.zAdd('racer_scores', [
{ score: 8, value: 'Sam-Bodden' },
{ score: 10, value: 'Royce' },
{ score: 6, value: 'Ford' },
{ score: 14, value: 'Prickett' },
{ score: 12, value: 'Castilla' }
]);
console.log(res3); // >>> 4
const res4 = await client.zRange('racer_scores', 0, -1);
console.log(res4); // >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce', 'Castilla', 'Prickett']
const res6 = await client.zRangeWithScores('racer_scores', 0, -1);
console.log(res6);
// >>> [
// { value: 'Ford', score: 6 }, { value: 'Sam-Bodden', score: 8 },
// { value: 'Norem', score: 10 }, { value: 'Royce', score: 10 },
// { value: 'Castilla', score: 12 }, { value: 'Prickett', score: 14 }
// ]
const res7 = await client.zRangeByScore('racer_scores', '-inf', 10);
console.log(res7); // >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce']
const res8 = await client.zRem('racer_scores', 'Castilla');
console.log(res8); // >>> 1
const res9 = await client.zRemRangeByScore('racer_scores', '-inf', 9);
console.log(res9); // >>> 2
const res10 = await client.zRange('racer_scores', 0, -1);
console.log(res10); // >>> ['Norem', 'Royce', 'Prickett']
const res11 = await client.zRank('racer_scores', 'Norem');
console.log(res11); // >>> 0
const res12 = await client.zRevRank('racer_scores', 'Norem');
console.log(res12); // >>> 2
const res13 = await client.zAdd('racer_scores', [
{ score: 0, value: 'Norem' },
{ score: 0, value: 'Sam-Bodden' },
{ score: 0, value: 'Royce' },
{ score: 0, value: 'Ford' },
{ score: 0, value: 'Prickett' },
{ score: 0, value: 'Castilla' }
]);
console.log(res13); // >>> 3
const res14 = await client.zRange('racer_scores', 0, -1);
console.log(res14); // >>> ['Castilla', 'Ford', 'Norem', 'Prickett', 'Royce', 'Sam-Bodden']
const res15 = await client.zRangeByLex('racer_scores', '[A', '[L');
console.log(res15); // >>> ['Castilla', 'Ford']
const res16 = await client.zAdd('racer_scores', { score: 100, value: 'Wood' });
console.log(res16); // >>> 1
const res17 = await client.zAdd('racer_scores', { score: 100, value: 'Henshaw' });
console.log(res17); // >>> 1
const res18 = await client.zAdd('racer_scores', { score: 150, value: 'Henshaw' }, { nx: true });
console.log(res18); // >>> 0
const res19 = await client.zIncrBy('racer_scores', 50, 'Wood');
console.log(res19); // >>> 150.0
const res20 = await client.zIncrBy('racer_scores', 50, 'Henshaw');
console.log(res20); // >>> 200.0
package io.redis.examples;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.resps.Tuple;
public class SortedSetsExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
long res1 = jedis.zadd("racer_scores", 10d, "Norem");
System.out.println(res1); // >>> 1
long res2 = jedis.zadd("racer_scores", 12d, "Castilla");
System.out.println(res2); // >>> 1
long res3 = jedis.zadd("racer_scores", new HashMap<String,Double>() {{
put("Sam-Bodden", 8d);
put("Royce", 10d);
put("Ford", 6d);
put("Prickett", 14d);
put("Castilla", 12d);
}});
System.out.println(res3); // >>> 4
List<String> res4 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res4); // >>> [Ford, Sam-Bodden, Norem, Royce, Castil, Castilla, Prickett]
List<String> res5 = jedis.zrevrange("racer_scores", 0, -1);
System.out.println(res5); // >>> [Prickett, Castilla, Castil, Royce, Norem, Sam-Bodden, Ford]
List<Tuple> res6 = jedis.zrangeWithScores("racer_scores", 0, -1);
System.out.println(res6); // >>> [[Ford,6.0], [Sam-Bodden,8.0], [Norem,10.0], [Royce,10.0], [Castil,12.0], [Castilla,12.0], [Prickett,14.0]]
List<String> res7 = jedis.zrangeByScore("racer_scores", Double.MIN_VALUE, 10d);
System.out.println(res7); // >>> [Ford, Sam-Bodden, Norem, Royce]
long res8 = jedis.zrem("racer_scores", "Castilla");
System.out.println(res8); // >>> 1
long res9 = jedis.zremrangeByScore("racer_scores", Double.MIN_VALUE, 9d);
System.out.println(res9); // >>> 2
List<String> res10 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res10); // >>> [Norem, Royce, Prickett]
long res11 = jedis.zrank("racer_scores", "Norem");
System.out.println(res11); // >>> 0
long res12 = jedis.zrevrank("racer_scores", "Norem");
System.out.println(res12); // >>> 2
long res13 = jedis.zadd("racer_scores", new HashMap<String,Double>() {{
put("Norem", 0d);
put("Sam-Bodden", 0d);
put("Royce", 0d);
put("Ford", 0d);
put("Prickett", 0d);
put("Castilla", 0d);
}});
System.out.println(res13); // >>> 3
List<String> res14 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res14); // >>> [Castilla, Ford, Norem, Prickett, Royce, Sam-Bodden]
List<String> res15 = jedis.zrangeByLex("racer_scores", "[A", "[L");
System.out.println(res15); // >>> [Castilla, Ford]
long res16 = jedis.zadd("racer_scores", 100d, "Wood");
System.out.println(res16); // >>> 1
long res17 = jedis.zadd("racer_scores", 100d, "Henshaw");
System.out.println(res17); // >>> 1
long res18 = jedis.zadd("racer_scores", 100d, "Henshaw");
System.out.println(res18); // >>> 0
double res19 = jedis.zincrby("racer_scores", 50d, "Wood");
System.out.println(res19); // >>> 150.0
double res20 = jedis.zincrby("racer_scores", 50d, "Henshaw");
System.out.println(res20); // >>> 200.0
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_zadd() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> 1
res2, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> 1
res3, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> 4
}
func ExampleClient_zrange() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> [Ford Sam-Bodden Norem Royce Castilla Prickett]
res5, err := rdb.ZRevRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> [Prickett Castilla Royce Norem Sam-Bodden Ford]
}
func ExampleClient_zrangewithscores() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res6, err := rdb.ZRangeWithScores(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res6)
// >>> [{6 Ford} {8 Sam-Bodden} {10 Norem} {10 Royce} {12 Castilla} {14 Prickett}]
}
func ExampleClient_zrangebyscore() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res7, err := rdb.ZRangeByScore(ctx, "racer_scores",
&redis.ZRangeBy{Min: "-inf", Max: "10"},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res7)
// >>> [Ford Sam-Bodden Norem Royce]
}
func ExampleClient_zremrangebyscore() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res8, err := rdb.ZRem(ctx, "racer_scores", "Castilla").Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> 1
res9, err := rdb.ZRemRangeByScore(ctx, "racer_scores", "-inf", "9").Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> 2
res10, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res10)
// >>> [Norem Royce Prickett]
}
func ExampleClient_zrank() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Prickett", Score: 14},
).Result()
if err != nil {
panic(err)
}
res11, err := rdb.ZRank(ctx, "racer_scores", "Norem").Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> 0
res12, err := rdb.ZRevRank(ctx, "racer_scores", "Norem").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> 2
}
func ExampleClient_zaddlex() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 0},
redis.Z{Member: "Royce", Score: 0},
redis.Z{Member: "Prickett", Score: 0},
).Result()
res13, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 0},
redis.Z{Member: "Sam-Bodden", Score: 0},
redis.Z{Member: "Royce", Score: 0},
redis.Z{Member: "Ford", Score: 0},
redis.Z{Member: "Prickett", Score: 0},
redis.Z{Member: "Castilla", Score: 0},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> 3
res14, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res14)
// >>> [Castilla Ford Norem Prickett Royce Sam-Bodden]
res15, err := rdb.ZRangeByLex(ctx, "racer_scores", &redis.ZRangeBy{
Min: "[A", Max: "[L",
}).Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [Castilla Ford]
}
func ExampleClient_leaderboard() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Wood", Score: 100},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> 1
res17, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Henshaw", Score: 100},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> 1
res18, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Henshaw", Score: 150},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> 0
res19, err := rdb.ZIncrBy(ctx, "racer_scores", 50, "Wood").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> 150
res20, err := rdb.ZIncrBy(ctx, "racer_scores", 50, "Henshaw").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> 200
}
using StackExchange.Redis;
public class SortedSetExample
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.SortedSetAdd("racer_scores", "Norem", 10);
Console.WriteLine(res1); // >>> True
bool res2 = db.SortedSetAdd("racer_scores", "Castilla", 12);
Console.WriteLine(res2); // >>> True
long res3 = db.SortedSetAdd("racer_scores", new[]{
new SortedSetEntry("Sam-Bodden", 8),
new SortedSetEntry("Royce", 10),
new SortedSetEntry("Ford", 6),
new SortedSetEntry("Prickett", 14),
new SortedSetEntry("Castilla", 12)
});
Console.WriteLine(res3); // >>> 4
RedisValue[] res4 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res4)); // >>> Ford, Sam-Bodden, Norem, Royce, Castilla, Prickett
RedisValue[] res5 = db.SortedSetRangeByRank("racer_scores", 0, -1, Order.Descending);
Console.WriteLine(string.Join(", ", res5)); // >>> Prickett, Castilla, Royce, Norem, Sam-Bodden, Ford
SortedSetEntry[] res6 = db.SortedSetRangeByRankWithScores("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res6)); // >>> Ford: 6, Sam-Bodden: 8, Norem: 10, Royce: 10, Castilla: 12, Prickett: 14
RedisValue[] res7 = db.SortedSetRangeByScore("racer_scores", double.NegativeInfinity, 10);
Console.WriteLine(string.Join(", ", res7)); // >>> Ford, Sam-Bodden, Norem, Royce
bool res8 = db.SortedSetRemove("racer_scores", "Castilla");
Console.WriteLine(res8); // >>> True
long res9 = db.SortedSetRemoveRangeByScore("racer_scores", double.NegativeInfinity, 9);
Console.WriteLine(res9); // >>> 2
RedisValue[] res10 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res10)); // >>> Norem, Royce, Prickett
long? res11 = db.SortedSetRank("racer_scores", "Norem");
Console.WriteLine(res11); // >>> 0
long? res12 = db.SortedSetRank("racer_scores", "Norem", Order.Descending);
Console.WriteLine(res12); // >>> 2
long res13 = db.SortedSetAdd("racer_scores", new[] {
new SortedSetEntry("Norem", 0),
new SortedSetEntry("Sam-Bodden", 0),
new SortedSetEntry("Royce", 0),
new SortedSetEntry("Ford", 0),
new SortedSetEntry("Prickett", 0),
new SortedSetEntry("Castilla", 0)
});
Console.WriteLine(res13); // >>> 3
RedisValue[] res14 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res14)); // >>> Castilla, Ford, Norem, Pricket, Royce, Sam-Bodden
RedisValue[] res15 = db.SortedSetRangeByValue("racer_scores", "A", "L", Exclude.None);
Console.WriteLine(string.Join(", ", res15)); // >>> Castilla, Ford
bool res16 = db.SortedSetAdd("racer_scores", "Wood", 100);
Console.WriteLine(res16); // >>> True
bool res17 = db.SortedSetAdd("racer_scores", "Henshaw", 100);
Console.WriteLine(res17); // >>> True
bool res18 = db.SortedSetAdd("racer_scores", "Henshaw", 150);
Console.WriteLine(res18); // >>> False
double res19 = db.SortedSetIncrement("racer_scores", "Wood", 50);
Console.WriteLine(res19); // >>> 150.0
double res20 = db.SortedSetIncrement("racer_scores", "Henshaw", 50);
Console.WriteLine(res20); // >>> 200.0
}
}
ZREMRANGEBYSCORE
is perhaps not the best command name,
but it can be very useful, and returns the number of removed elements.
Another extremely useful operation defined for sorted set elements
is the get-rank operation. It is possible to ask what is the
position of an element in the set of ordered elements.
The ZREVRANK
command is also available in order to get the rank, considering
the elements sorted in a descending way.
> ZRANK racer_scores "Norem"
(integer) 0
> ZREVRANK racer_scores "Norem"
(integer) 3
"""
Code samples for Sorted set doc pages:
https://redis.io/docs/latest/develop/data-types/sorted-sets/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.zadd("racer_scores", {"Norem": 10})
print(res1) # >>> 1
res2 = r.zadd("racer_scores", {"Castilla": 12})
print(res2) # >>> 1
res3 = r.zadd(
"racer_scores",
{"Sam-Bodden": 8, "Royce": 10, "Ford": 6, "Prickett": 14, "Castilla": 12},
)
print(res3) # >>> 4
res4 = r.zrange("racer_scores", 0, -1)
print(res4) # >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce', 'Castilla', 'Prickett']
res5 = r.zrevrange("racer_scores", 0, -1)
print(res5) # >>> ['Prickett', 'Castilla', 'Royce', 'Norem', 'Sam-Bodden', 'Ford']
res6 = r.zrange("racer_scores", 0, -1, withscores=True)
print(
res6
)
# >>> [
# ('Ford', 6.0), ('Sam-Bodden', 8.0), ('Norem', 10.0), ('Royce', 10.0),
# ('Castilla', 12.0), ('Prickett', 14.0)
# ]
res7 = r.zrangebyscore("racer_scores", "-inf", 10)
print(res7) # >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce']
res8 = r.zrem("racer_scores", "Castilla")
print(res8) # >>> 1
res9 = r.zremrangebyscore("racer_scores", "-inf", 9)
print(res9) # >>> 2
res10 = r.zrange("racer_scores", 0, -1)
print(res10) # >>> ['Norem', 'Royce', 'Prickett']
res11 = r.zrank("racer_scores", "Norem")
print(res11) # >>> 0
res12 = r.zrevrank("racer_scores", "Norem")
print(res12) # >>> 2
res13 = r.zadd(
"racer_scores",
{
"Norem": 0,
"Sam-Bodden": 0,
"Royce": 0,
"Ford": 0,
"Prickett": 0,
"Castilla": 0,
},
)
print(res13) # >>> 3
res14 = r.zrange("racer_scores", 0, -1)
print(res14) # >>> ['Castilla', 'Ford', 'Norem', 'Prickett', 'Royce', 'Sam-Bodden']
res15 = r.zrangebylex("racer_scores", "[A", "[L")
print(res15) # >>> ['Castilla', 'Ford']
res16 = r.zadd("racer_scores", {"Wood": 100})
print(res16) # >>> 1
res17 = r.zadd("racer_scores", {"Henshaw": 100})
print(res17) # >>> 1
res18 = r.zadd("racer_scores", {"Henshaw": 150})
print(res18) # >>> 0
res19 = r.zincrby("racer_scores", 50, "Wood")
print(res19) # >>> 150.0
res20 = r.zincrby("racer_scores", 50, "Henshaw")
print(res20) # >>> 200.0
import assert from 'assert';
import { createClient } from 'redis';
const client = createClient();
await client.connect();
const res1 = await client.zAdd('racer_scores', { score: 10, value: 'Norem' });
console.log(res1); // >>> 1
const res2 = await client.zAdd('racer_scores', { score: 12, value: 'Castilla' });
console.log(res2); // >>> 1
const res3 = await client.zAdd('racer_scores', [
{ score: 8, value: 'Sam-Bodden' },
{ score: 10, value: 'Royce' },
{ score: 6, value: 'Ford' },
{ score: 14, value: 'Prickett' },
{ score: 12, value: 'Castilla' }
]);
console.log(res3); // >>> 4
const res4 = await client.zRange('racer_scores', 0, -1);
console.log(res4); // >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce', 'Castilla', 'Prickett']
const res6 = await client.zRangeWithScores('racer_scores', 0, -1);
console.log(res6);
// >>> [
// { value: 'Ford', score: 6 }, { value: 'Sam-Bodden', score: 8 },
// { value: 'Norem', score: 10 }, { value: 'Royce', score: 10 },
// { value: 'Castilla', score: 12 }, { value: 'Prickett', score: 14 }
// ]
const res7 = await client.zRangeByScore('racer_scores', '-inf', 10);
console.log(res7); // >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce']
const res8 = await client.zRem('racer_scores', 'Castilla');
console.log(res8); // >>> 1
const res9 = await client.zRemRangeByScore('racer_scores', '-inf', 9);
console.log(res9); // >>> 2
const res10 = await client.zRange('racer_scores', 0, -1);
console.log(res10); // >>> ['Norem', 'Royce', 'Prickett']
const res11 = await client.zRank('racer_scores', 'Norem');
console.log(res11); // >>> 0
const res12 = await client.zRevRank('racer_scores', 'Norem');
console.log(res12); // >>> 2
const res13 = await client.zAdd('racer_scores', [
{ score: 0, value: 'Norem' },
{ score: 0, value: 'Sam-Bodden' },
{ score: 0, value: 'Royce' },
{ score: 0, value: 'Ford' },
{ score: 0, value: 'Prickett' },
{ score: 0, value: 'Castilla' }
]);
console.log(res13); // >>> 3
const res14 = await client.zRange('racer_scores', 0, -1);
console.log(res14); // >>> ['Castilla', 'Ford', 'Norem', 'Prickett', 'Royce', 'Sam-Bodden']
const res15 = await client.zRangeByLex('racer_scores', '[A', '[L');
console.log(res15); // >>> ['Castilla', 'Ford']
const res16 = await client.zAdd('racer_scores', { score: 100, value: 'Wood' });
console.log(res16); // >>> 1
const res17 = await client.zAdd('racer_scores', { score: 100, value: 'Henshaw' });
console.log(res17); // >>> 1
const res18 = await client.zAdd('racer_scores', { score: 150, value: 'Henshaw' }, { nx: true });
console.log(res18); // >>> 0
const res19 = await client.zIncrBy('racer_scores', 50, 'Wood');
console.log(res19); // >>> 150.0
const res20 = await client.zIncrBy('racer_scores', 50, 'Henshaw');
console.log(res20); // >>> 200.0
package io.redis.examples;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.resps.Tuple;
public class SortedSetsExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
long res1 = jedis.zadd("racer_scores", 10d, "Norem");
System.out.println(res1); // >>> 1
long res2 = jedis.zadd("racer_scores", 12d, "Castilla");
System.out.println(res2); // >>> 1
long res3 = jedis.zadd("racer_scores", new HashMap<String,Double>() {{
put("Sam-Bodden", 8d);
put("Royce", 10d);
put("Ford", 6d);
put("Prickett", 14d);
put("Castilla", 12d);
}});
System.out.println(res3); // >>> 4
List<String> res4 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res4); // >>> [Ford, Sam-Bodden, Norem, Royce, Castil, Castilla, Prickett]
List<String> res5 = jedis.zrevrange("racer_scores", 0, -1);
System.out.println(res5); // >>> [Prickett, Castilla, Castil, Royce, Norem, Sam-Bodden, Ford]
List<Tuple> res6 = jedis.zrangeWithScores("racer_scores", 0, -1);
System.out.println(res6); // >>> [[Ford,6.0], [Sam-Bodden,8.0], [Norem,10.0], [Royce,10.0], [Castil,12.0], [Castilla,12.0], [Prickett,14.0]]
List<String> res7 = jedis.zrangeByScore("racer_scores", Double.MIN_VALUE, 10d);
System.out.println(res7); // >>> [Ford, Sam-Bodden, Norem, Royce]
long res8 = jedis.zrem("racer_scores", "Castilla");
System.out.println(res8); // >>> 1
long res9 = jedis.zremrangeByScore("racer_scores", Double.MIN_VALUE, 9d);
System.out.println(res9); // >>> 2
List<String> res10 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res10); // >>> [Norem, Royce, Prickett]
long res11 = jedis.zrank("racer_scores", "Norem");
System.out.println(res11); // >>> 0
long res12 = jedis.zrevrank("racer_scores", "Norem");
System.out.println(res12); // >>> 2
long res13 = jedis.zadd("racer_scores", new HashMap<String,Double>() {{
put("Norem", 0d);
put("Sam-Bodden", 0d);
put("Royce", 0d);
put("Ford", 0d);
put("Prickett", 0d);
put("Castilla", 0d);
}});
System.out.println(res13); // >>> 3
List<String> res14 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res14); // >>> [Castilla, Ford, Norem, Prickett, Royce, Sam-Bodden]
List<String> res15 = jedis.zrangeByLex("racer_scores", "[A", "[L");
System.out.println(res15); // >>> [Castilla, Ford]
long res16 = jedis.zadd("racer_scores", 100d, "Wood");
System.out.println(res16); // >>> 1
long res17 = jedis.zadd("racer_scores", 100d, "Henshaw");
System.out.println(res17); // >>> 1
long res18 = jedis.zadd("racer_scores", 100d, "Henshaw");
System.out.println(res18); // >>> 0
double res19 = jedis.zincrby("racer_scores", 50d, "Wood");
System.out.println(res19); // >>> 150.0
double res20 = jedis.zincrby("racer_scores", 50d, "Henshaw");
System.out.println(res20); // >>> 200.0
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_zadd() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> 1
res2, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> 1
res3, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> 4
}
func ExampleClient_zrange() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> [Ford Sam-Bodden Norem Royce Castilla Prickett]
res5, err := rdb.ZRevRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> [Prickett Castilla Royce Norem Sam-Bodden Ford]
}
func ExampleClient_zrangewithscores() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res6, err := rdb.ZRangeWithScores(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res6)
// >>> [{6 Ford} {8 Sam-Bodden} {10 Norem} {10 Royce} {12 Castilla} {14 Prickett}]
}
func ExampleClient_zrangebyscore() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res7, err := rdb.ZRangeByScore(ctx, "racer_scores",
&redis.ZRangeBy{Min: "-inf", Max: "10"},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res7)
// >>> [Ford Sam-Bodden Norem Royce]
}
func ExampleClient_zremrangebyscore() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res8, err := rdb.ZRem(ctx, "racer_scores", "Castilla").Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> 1
res9, err := rdb.ZRemRangeByScore(ctx, "racer_scores", "-inf", "9").Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> 2
res10, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res10)
// >>> [Norem Royce Prickett]
}
func ExampleClient_zrank() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Prickett", Score: 14},
).Result()
if err != nil {
panic(err)
}
res11, err := rdb.ZRank(ctx, "racer_scores", "Norem").Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> 0
res12, err := rdb.ZRevRank(ctx, "racer_scores", "Norem").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> 2
}
func ExampleClient_zaddlex() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 0},
redis.Z{Member: "Royce", Score: 0},
redis.Z{Member: "Prickett", Score: 0},
).Result()
res13, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 0},
redis.Z{Member: "Sam-Bodden", Score: 0},
redis.Z{Member: "Royce", Score: 0},
redis.Z{Member: "Ford", Score: 0},
redis.Z{Member: "Prickett", Score: 0},
redis.Z{Member: "Castilla", Score: 0},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> 3
res14, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res14)
// >>> [Castilla Ford Norem Prickett Royce Sam-Bodden]
res15, err := rdb.ZRangeByLex(ctx, "racer_scores", &redis.ZRangeBy{
Min: "[A", Max: "[L",
}).Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [Castilla Ford]
}
func ExampleClient_leaderboard() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Wood", Score: 100},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> 1
res17, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Henshaw", Score: 100},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> 1
res18, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Henshaw", Score: 150},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> 0
res19, err := rdb.ZIncrBy(ctx, "racer_scores", 50, "Wood").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> 150
res20, err := rdb.ZIncrBy(ctx, "racer_scores", 50, "Henshaw").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> 200
}
using StackExchange.Redis;
public class SortedSetExample
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.SortedSetAdd("racer_scores", "Norem", 10);
Console.WriteLine(res1); // >>> True
bool res2 = db.SortedSetAdd("racer_scores", "Castilla", 12);
Console.WriteLine(res2); // >>> True
long res3 = db.SortedSetAdd("racer_scores", new[]{
new SortedSetEntry("Sam-Bodden", 8),
new SortedSetEntry("Royce", 10),
new SortedSetEntry("Ford", 6),
new SortedSetEntry("Prickett", 14),
new SortedSetEntry("Castilla", 12)
});
Console.WriteLine(res3); // >>> 4
RedisValue[] res4 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res4)); // >>> Ford, Sam-Bodden, Norem, Royce, Castilla, Prickett
RedisValue[] res5 = db.SortedSetRangeByRank("racer_scores", 0, -1, Order.Descending);
Console.WriteLine(string.Join(", ", res5)); // >>> Prickett, Castilla, Royce, Norem, Sam-Bodden, Ford
SortedSetEntry[] res6 = db.SortedSetRangeByRankWithScores("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res6)); // >>> Ford: 6, Sam-Bodden: 8, Norem: 10, Royce: 10, Castilla: 12, Prickett: 14
RedisValue[] res7 = db.SortedSetRangeByScore("racer_scores", double.NegativeInfinity, 10);
Console.WriteLine(string.Join(", ", res7)); // >>> Ford, Sam-Bodden, Norem, Royce
bool res8 = db.SortedSetRemove("racer_scores", "Castilla");
Console.WriteLine(res8); // >>> True
long res9 = db.SortedSetRemoveRangeByScore("racer_scores", double.NegativeInfinity, 9);
Console.WriteLine(res9); // >>> 2
RedisValue[] res10 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res10)); // >>> Norem, Royce, Prickett
long? res11 = db.SortedSetRank("racer_scores", "Norem");
Console.WriteLine(res11); // >>> 0
long? res12 = db.SortedSetRank("racer_scores", "Norem", Order.Descending);
Console.WriteLine(res12); // >>> 2
long res13 = db.SortedSetAdd("racer_scores", new[] {
new SortedSetEntry("Norem", 0),
new SortedSetEntry("Sam-Bodden", 0),
new SortedSetEntry("Royce", 0),
new SortedSetEntry("Ford", 0),
new SortedSetEntry("Prickett", 0),
new SortedSetEntry("Castilla", 0)
});
Console.WriteLine(res13); // >>> 3
RedisValue[] res14 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res14)); // >>> Castilla, Ford, Norem, Pricket, Royce, Sam-Bodden
RedisValue[] res15 = db.SortedSetRangeByValue("racer_scores", "A", "L", Exclude.None);
Console.WriteLine(string.Join(", ", res15)); // >>> Castilla, Ford
bool res16 = db.SortedSetAdd("racer_scores", "Wood", 100);
Console.WriteLine(res16); // >>> True
bool res17 = db.SortedSetAdd("racer_scores", "Henshaw", 100);
Console.WriteLine(res17); // >>> True
bool res18 = db.SortedSetAdd("racer_scores", "Henshaw", 150);
Console.WriteLine(res18); // >>> False
double res19 = db.SortedSetIncrement("racer_scores", "Wood", 50);
Console.WriteLine(res19); // >>> 150.0
double res20 = db.SortedSetIncrement("racer_scores", "Henshaw", 50);
Console.WriteLine(res20); // >>> 200.0
}
}
Lexicographical scores
In version Redis 2.8, a new feature was introduced that allows
getting ranges lexicographically, assuming elements in a sorted set are all
inserted with the same identical score (elements are compared with the C
memcmp
function, so it is guaranteed that there is no collation, and every
Redis instance will reply with the same output).
The main commands to operate with lexicographical ranges are ZRANGEBYLEX
,
ZREVRANGEBYLEX
, ZREMRANGEBYLEX
and ZLEXCOUNT
.
For example, let's add again our list of famous racers, but this time
using a score of zero for all the elements. We'll see that because of the sorted sets ordering rules, they are already sorted lexicographically. Using ZRANGEBYLEX
we can ask for lexicographical ranges:
> ZADD racer_scores 0 "Norem" 0 "Sam-Bodden" 0 "Royce" 0 "Castilla" 0 "Prickett" 0 "Ford"
(integer) 3
> ZRANGE racer_scores 0 -1
1) "Castilla"
2) "Ford"
3) "Norem"
4) "Prickett"
5) "Royce"
6) "Sam-Bodden"
> ZRANGEBYLEX racer_scores [A [L
1) "Castilla"
2) "Ford"
"""
Code samples for Sorted set doc pages:
https://redis.io/docs/latest/develop/data-types/sorted-sets/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.zadd("racer_scores", {"Norem": 10})
print(res1) # >>> 1
res2 = r.zadd("racer_scores", {"Castilla": 12})
print(res2) # >>> 1
res3 = r.zadd(
"racer_scores",
{"Sam-Bodden": 8, "Royce": 10, "Ford": 6, "Prickett": 14, "Castilla": 12},
)
print(res3) # >>> 4
res4 = r.zrange("racer_scores", 0, -1)
print(res4) # >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce', 'Castilla', 'Prickett']
res5 = r.zrevrange("racer_scores", 0, -1)
print(res5) # >>> ['Prickett', 'Castilla', 'Royce', 'Norem', 'Sam-Bodden', 'Ford']
res6 = r.zrange("racer_scores", 0, -1, withscores=True)
print(
res6
)
# >>> [
# ('Ford', 6.0), ('Sam-Bodden', 8.0), ('Norem', 10.0), ('Royce', 10.0),
# ('Castilla', 12.0), ('Prickett', 14.0)
# ]
res7 = r.zrangebyscore("racer_scores", "-inf", 10)
print(res7) # >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce']
res8 = r.zrem("racer_scores", "Castilla")
print(res8) # >>> 1
res9 = r.zremrangebyscore("racer_scores", "-inf", 9)
print(res9) # >>> 2
res10 = r.zrange("racer_scores", 0, -1)
print(res10) # >>> ['Norem', 'Royce', 'Prickett']
res11 = r.zrank("racer_scores", "Norem")
print(res11) # >>> 0
res12 = r.zrevrank("racer_scores", "Norem")
print(res12) # >>> 2
res13 = r.zadd(
"racer_scores",
{
"Norem": 0,
"Sam-Bodden": 0,
"Royce": 0,
"Ford": 0,
"Prickett": 0,
"Castilla": 0,
},
)
print(res13) # >>> 3
res14 = r.zrange("racer_scores", 0, -1)
print(res14) # >>> ['Castilla', 'Ford', 'Norem', 'Prickett', 'Royce', 'Sam-Bodden']
res15 = r.zrangebylex("racer_scores", "[A", "[L")
print(res15) # >>> ['Castilla', 'Ford']
res16 = r.zadd("racer_scores", {"Wood": 100})
print(res16) # >>> 1
res17 = r.zadd("racer_scores", {"Henshaw": 100})
print(res17) # >>> 1
res18 = r.zadd("racer_scores", {"Henshaw": 150})
print(res18) # >>> 0
res19 = r.zincrby("racer_scores", 50, "Wood")
print(res19) # >>> 150.0
res20 = r.zincrby("racer_scores", 50, "Henshaw")
print(res20) # >>> 200.0
import assert from 'assert';
import { createClient } from 'redis';
const client = createClient();
await client.connect();
const res1 = await client.zAdd('racer_scores', { score: 10, value: 'Norem' });
console.log(res1); // >>> 1
const res2 = await client.zAdd('racer_scores', { score: 12, value: 'Castilla' });
console.log(res2); // >>> 1
const res3 = await client.zAdd('racer_scores', [
{ score: 8, value: 'Sam-Bodden' },
{ score: 10, value: 'Royce' },
{ score: 6, value: 'Ford' },
{ score: 14, value: 'Prickett' },
{ score: 12, value: 'Castilla' }
]);
console.log(res3); // >>> 4
const res4 = await client.zRange('racer_scores', 0, -1);
console.log(res4); // >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce', 'Castilla', 'Prickett']
const res6 = await client.zRangeWithScores('racer_scores', 0, -1);
console.log(res6);
// >>> [
// { value: 'Ford', score: 6 }, { value: 'Sam-Bodden', score: 8 },
// { value: 'Norem', score: 10 }, { value: 'Royce', score: 10 },
// { value: 'Castilla', score: 12 }, { value: 'Prickett', score: 14 }
// ]
const res7 = await client.zRangeByScore('racer_scores', '-inf', 10);
console.log(res7); // >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce']
const res8 = await client.zRem('racer_scores', 'Castilla');
console.log(res8); // >>> 1
const res9 = await client.zRemRangeByScore('racer_scores', '-inf', 9);
console.log(res9); // >>> 2
const res10 = await client.zRange('racer_scores', 0, -1);
console.log(res10); // >>> ['Norem', 'Royce', 'Prickett']
const res11 = await client.zRank('racer_scores', 'Norem');
console.log(res11); // >>> 0
const res12 = await client.zRevRank('racer_scores', 'Norem');
console.log(res12); // >>> 2
const res13 = await client.zAdd('racer_scores', [
{ score: 0, value: 'Norem' },
{ score: 0, value: 'Sam-Bodden' },
{ score: 0, value: 'Royce' },
{ score: 0, value: 'Ford' },
{ score: 0, value: 'Prickett' },
{ score: 0, value: 'Castilla' }
]);
console.log(res13); // >>> 3
const res14 = await client.zRange('racer_scores', 0, -1);
console.log(res14); // >>> ['Castilla', 'Ford', 'Norem', 'Prickett', 'Royce', 'Sam-Bodden']
const res15 = await client.zRangeByLex('racer_scores', '[A', '[L');
console.log(res15); // >>> ['Castilla', 'Ford']
const res16 = await client.zAdd('racer_scores', { score: 100, value: 'Wood' });
console.log(res16); // >>> 1
const res17 = await client.zAdd('racer_scores', { score: 100, value: 'Henshaw' });
console.log(res17); // >>> 1
const res18 = await client.zAdd('racer_scores', { score: 150, value: 'Henshaw' }, { nx: true });
console.log(res18); // >>> 0
const res19 = await client.zIncrBy('racer_scores', 50, 'Wood');
console.log(res19); // >>> 150.0
const res20 = await client.zIncrBy('racer_scores', 50, 'Henshaw');
console.log(res20); // >>> 200.0
package io.redis.examples;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.resps.Tuple;
public class SortedSetsExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
long res1 = jedis.zadd("racer_scores", 10d, "Norem");
System.out.println(res1); // >>> 1
long res2 = jedis.zadd("racer_scores", 12d, "Castilla");
System.out.println(res2); // >>> 1
long res3 = jedis.zadd("racer_scores", new HashMap<String,Double>() {{
put("Sam-Bodden", 8d);
put("Royce", 10d);
put("Ford", 6d);
put("Prickett", 14d);
put("Castilla", 12d);
}});
System.out.println(res3); // >>> 4
List<String> res4 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res4); // >>> [Ford, Sam-Bodden, Norem, Royce, Castil, Castilla, Prickett]
List<String> res5 = jedis.zrevrange("racer_scores", 0, -1);
System.out.println(res5); // >>> [Prickett, Castilla, Castil, Royce, Norem, Sam-Bodden, Ford]
List<Tuple> res6 = jedis.zrangeWithScores("racer_scores", 0, -1);
System.out.println(res6); // >>> [[Ford,6.0], [Sam-Bodden,8.0], [Norem,10.0], [Royce,10.0], [Castil,12.0], [Castilla,12.0], [Prickett,14.0]]
List<String> res7 = jedis.zrangeByScore("racer_scores", Double.MIN_VALUE, 10d);
System.out.println(res7); // >>> [Ford, Sam-Bodden, Norem, Royce]
long res8 = jedis.zrem("racer_scores", "Castilla");
System.out.println(res8); // >>> 1
long res9 = jedis.zremrangeByScore("racer_scores", Double.MIN_VALUE, 9d);
System.out.println(res9); // >>> 2
List<String> res10 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res10); // >>> [Norem, Royce, Prickett]
long res11 = jedis.zrank("racer_scores", "Norem");
System.out.println(res11); // >>> 0
long res12 = jedis.zrevrank("racer_scores", "Norem");
System.out.println(res12); // >>> 2
long res13 = jedis.zadd("racer_scores", new HashMap<String,Double>() {{
put("Norem", 0d);
put("Sam-Bodden", 0d);
put("Royce", 0d);
put("Ford", 0d);
put("Prickett", 0d);
put("Castilla", 0d);
}});
System.out.println(res13); // >>> 3
List<String> res14 = jedis.zrange("racer_scores", 0, -1);
System.out.println(res14); // >>> [Castilla, Ford, Norem, Prickett, Royce, Sam-Bodden]
List<String> res15 = jedis.zrangeByLex("racer_scores", "[A", "[L");
System.out.println(res15); // >>> [Castilla, Ford]
long res16 = jedis.zadd("racer_scores", 100d, "Wood");
System.out.println(res16); // >>> 1
long res17 = jedis.zadd("racer_scores", 100d, "Henshaw");
System.out.println(res17); // >>> 1
long res18 = jedis.zadd("racer_scores", 100d, "Henshaw");
System.out.println(res18); // >>> 0
double res19 = jedis.zincrby("racer_scores", 50d, "Wood");
System.out.println(res19); // >>> 150.0
double res20 = jedis.zincrby("racer_scores", 50d, "Henshaw");
System.out.println(res20); // >>> 200.0
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_zadd() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> 1
res2, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> 1
res3, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> 4
}
func ExampleClient_zrange() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> [Ford Sam-Bodden Norem Royce Castilla Prickett]
res5, err := rdb.ZRevRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> [Prickett Castilla Royce Norem Sam-Bodden Ford]
}
func ExampleClient_zrangewithscores() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res6, err := rdb.ZRangeWithScores(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res6)
// >>> [{6 Ford} {8 Sam-Bodden} {10 Norem} {10 Royce} {12 Castilla} {14 Prickett}]
}
func ExampleClient_zrangebyscore() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res7, err := rdb.ZRangeByScore(ctx, "racer_scores",
&redis.ZRangeBy{Min: "-inf", Max: "10"},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res7)
// >>> [Ford Sam-Bodden Norem Royce]
}
func ExampleClient_zremrangebyscore() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Sam-Bodden", Score: 8},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Ford", Score: 6},
redis.Z{Member: "Prickett", Score: 14},
redis.Z{Member: "Castilla", Score: 12},
).Result()
if err != nil {
panic(err)
}
res8, err := rdb.ZRem(ctx, "racer_scores", "Castilla").Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> 1
res9, err := rdb.ZRemRangeByScore(ctx, "racer_scores", "-inf", "9").Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> 2
res10, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res10)
// >>> [Norem Royce Prickett]
}
func ExampleClient_zrank() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 10},
redis.Z{Member: "Royce", Score: 10},
redis.Z{Member: "Prickett", Score: 14},
).Result()
if err != nil {
panic(err)
}
res11, err := rdb.ZRank(ctx, "racer_scores", "Norem").Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> 0
res12, err := rdb.ZRevRank(ctx, "racer_scores", "Norem").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> 2
}
func ExampleClient_zaddlex() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 0},
redis.Z{Member: "Royce", Score: 0},
redis.Z{Member: "Prickett", Score: 0},
).Result()
res13, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Norem", Score: 0},
redis.Z{Member: "Sam-Bodden", Score: 0},
redis.Z{Member: "Royce", Score: 0},
redis.Z{Member: "Ford", Score: 0},
redis.Z{Member: "Prickett", Score: 0},
redis.Z{Member: "Castilla", Score: 0},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> 3
res14, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res14)
// >>> [Castilla Ford Norem Prickett Royce Sam-Bodden]
res15, err := rdb.ZRangeByLex(ctx, "racer_scores", &redis.ZRangeBy{
Min: "[A", Max: "[L",
}).Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [Castilla Ford]
}
func ExampleClient_leaderboard() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Wood", Score: 100},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> 1
res17, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Henshaw", Score: 100},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> 1
res18, err := rdb.ZAdd(ctx, "racer_scores",
redis.Z{Member: "Henshaw", Score: 150},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> 0
res19, err := rdb.ZIncrBy(ctx, "racer_scores", 50, "Wood").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> 150
res20, err := rdb.ZIncrBy(ctx, "racer_scores", 50, "Henshaw").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> 200
}
using StackExchange.Redis;
public class SortedSetExample
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.SortedSetAdd("racer_scores", "Norem", 10);
Console.WriteLine(res1); // >>> True
bool res2 = db.SortedSetAdd("racer_scores", "Castilla", 12);
Console.WriteLine(res2); // >>> True
long res3 = db.SortedSetAdd("racer_scores", new[]{
new SortedSetEntry("Sam-Bodden", 8),
new SortedSetEntry("Royce", 10),
new SortedSetEntry("Ford", 6),
new SortedSetEntry("Prickett", 14),
new SortedSetEntry("Castilla", 12)
});
Console.WriteLine(res3); // >>> 4
RedisValue[] res4 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res4)); // >>> Ford, Sam-Bodden, Norem, Royce, Castilla, Prickett
RedisValue[] res5 = db.SortedSetRangeByRank("racer_scores", 0, -1, Order.Descending);
Console.WriteLine(string.Join(", ", res5)); // >>> Prickett, Castilla, Royce, Norem, Sam-Bodden, Ford
SortedSetEntry[] res6 = db.SortedSetRangeByRankWithScores("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res6)); // >>> Ford: 6, Sam-Bodden: 8, Norem: 10, Royce: 10, Castilla: 12, Prickett: 14
RedisValue[] res7 = db.SortedSetRangeByScore("racer_scores", double.NegativeInfinity, 10);
Console.WriteLine(string.Join(", ", res7)); // >>> Ford, Sam-Bodden, Norem, Royce
bool res8 = db.SortedSetRemove("racer_scores", "Castilla");
Console.WriteLine(res8); // >>> True
long res9 = db.SortedSetRemoveRangeByScore("racer_scores", double.NegativeInfinity, 9);
Console.WriteLine(res9); // >>> 2
RedisValue[] res10 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res10)); // >>> Norem, Royce, Prickett
long? res11 = db.SortedSetRank("racer_scores", "Norem");
Console.WriteLine(res11); // >>> 0
long? res12 = db.SortedSetRank("racer_scores", "Norem", Order.Descending);
Console.WriteLine(res12); // >>> 2
long res13 = db.SortedSetAdd("racer_scores", new[] {
new SortedSetEntry("Norem", 0),
new SortedSetEntry("Sam-Bodden", 0),
new SortedSetEntry("Royce", 0),
new SortedSetEntry("Ford", 0),
new SortedSetEntry("Prickett", 0),
new SortedSetEntry("Castilla", 0)
});
Console.WriteLine(res13); // >>> 3
RedisValue[] res14 = db.SortedSetRangeByRank("racer_scores", 0, -1);
Console.WriteLine(string.Join(", ", res14)); // >>> Castilla, Ford, Norem, Pricket, Royce, Sam-Bodden
RedisValue[] res15 = db.SortedSetRangeByValue("racer_scores", "A", "L", Exclude.None);
Console.WriteLine(string.Join(", ", res15)); // >>> Castilla, Ford
bool res16 = db.SortedSetAdd("racer_scores", "Wood", 100);
Console.WriteLine(res16); // >>> True
bool res17 = db.SortedSetAdd("racer_scores", "Henshaw", 100);
Console.WriteLine(res17); // >>> True
bool res18 = db.SortedSetAdd("racer_scores", "Henshaw", 150);
Console.WriteLine(res18); // >>> False
double res19 = db.SortedSetIncrement("racer_scores", "Wood", 50);
Console.WriteLine(res19); // >>> 150.0
double res20 = db.SortedSetIncrement("racer_scores", "Henshaw", 50);
Console.WriteLine(res20); // >>> 200.0
}
}
Ranges can be inclusive or exclusive (depending on the first character),
also string infinite and minus infinite are specified respectively with
the +
and -
strings. See the documentation for more information.
This feature is important because it allows us to use sorted sets as a generic index. For example, if you want to index elements by a 128-bit unsigned integer argument, all you need to do is to add elements into a sorted set with the same score (for example 0) but with a 16 byte prefix consisting of the 128 bit number in big endian. Since numbers in big endian, when ordered lexicographically (in raw bytes order) are actually ordered numerically as well, you can ask for ranges in the 128 bit space, and get the element's value discarding the prefix
Updating the score: leaderboards
Just a final note about sorted sets before switching to the next topic.
Sorted sets' scores can be updated at any time. Just calling ZADD
against
an element already included in the sorted set will update its score
(and position) with O(log(N)) time complexity. As such, sorted sets are suitable
when there are tons of updates.
Because of this characteristic a common use case is leaderboards. The typical application is a Facebook game where you combine the ability to take users sorted by their high score, plus the get-rank operation, in order to show the top-N users, and the user rank in the leader board (e.g., "you are the #4932 best score here").
Examples
- There are two ways we can use a sorted set to represent a leaderboard. If we know a racer's new score, we can update it directly via the
ZADD
command. However, if we want to add points to an existing score, we can use theZINCRBY
command.> ZADD racer_scores 100 "Wood" (integer) 1 > ZADD racer_scores 100 "Henshaw" (integer) 1 > ZADD racer_scores 150 "Henshaw" (integer) 0 > ZINCRBY racer_scores 50 "Wood" "150" > ZINCRBY racer_scores 50 "Henshaw" "200"
Are you tired of using redis-cli? Try Redis Insight - the developer GUI for Redis.""" Code samples for Sorted set doc pages: https://redis.io/docs/latest/develop/data-types/sorted-sets/ """ import redis r = redis.Redis(decode_responses=True) res1 = r.zadd("racer_scores", {"Norem": 10}) print(res1) # >>> 1 res2 = r.zadd("racer_scores", {"Castilla": 12}) print(res2) # >>> 1 res3 = r.zadd( "racer_scores", {"Sam-Bodden": 8, "Royce": 10, "Ford": 6, "Prickett": 14, "Castilla": 12}, ) print(res3) # >>> 4 res4 = r.zrange("racer_scores", 0, -1) print(res4) # >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce', 'Castilla', 'Prickett'] res5 = r.zrevrange("racer_scores", 0, -1) print(res5) # >>> ['Prickett', 'Castilla', 'Royce', 'Norem', 'Sam-Bodden', 'Ford'] res6 = r.zrange("racer_scores", 0, -1, withscores=True) print( res6 ) # >>> [ # ('Ford', 6.0), ('Sam-Bodden', 8.0), ('Norem', 10.0), ('Royce', 10.0), # ('Castilla', 12.0), ('Prickett', 14.0) # ] res7 = r.zrangebyscore("racer_scores", "-inf", 10) print(res7) # >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce'] res8 = r.zrem("racer_scores", "Castilla") print(res8) # >>> 1 res9 = r.zremrangebyscore("racer_scores", "-inf", 9) print(res9) # >>> 2 res10 = r.zrange("racer_scores", 0, -1) print(res10) # >>> ['Norem', 'Royce', 'Prickett'] res11 = r.zrank("racer_scores", "Norem") print(res11) # >>> 0 res12 = r.zrevrank("racer_scores", "Norem") print(res12) # >>> 2 res13 = r.zadd( "racer_scores", { "Norem": 0, "Sam-Bodden": 0, "Royce": 0, "Ford": 0, "Prickett": 0, "Castilla": 0, }, ) print(res13) # >>> 3 res14 = r.zrange("racer_scores", 0, -1) print(res14) # >>> ['Castilla', 'Ford', 'Norem', 'Prickett', 'Royce', 'Sam-Bodden'] res15 = r.zrangebylex("racer_scores", "[A", "[L") print(res15) # >>> ['Castilla', 'Ford'] res16 = r.zadd("racer_scores", {"Wood": 100}) print(res16) # >>> 1 res17 = r.zadd("racer_scores", {"Henshaw": 100}) print(res17) # >>> 1 res18 = r.zadd("racer_scores", {"Henshaw": 150}) print(res18) # >>> 0 res19 = r.zincrby("racer_scores", 50, "Wood") print(res19) # >>> 150.0 res20 = r.zincrby("racer_scores", 50, "Henshaw") print(res20) # >>> 200.0
import assert from 'assert'; import { createClient } from 'redis'; const client = createClient(); await client.connect(); const res1 = await client.zAdd('racer_scores', { score: 10, value: 'Norem' }); console.log(res1); // >>> 1 const res2 = await client.zAdd('racer_scores', { score: 12, value: 'Castilla' }); console.log(res2); // >>> 1 const res3 = await client.zAdd('racer_scores', [ { score: 8, value: 'Sam-Bodden' }, { score: 10, value: 'Royce' }, { score: 6, value: 'Ford' }, { score: 14, value: 'Prickett' }, { score: 12, value: 'Castilla' } ]); console.log(res3); // >>> 4 const res4 = await client.zRange('racer_scores', 0, -1); console.log(res4); // >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce', 'Castilla', 'Prickett'] const res6 = await client.zRangeWithScores('racer_scores', 0, -1); console.log(res6); // >>> [ // { value: 'Ford', score: 6 }, { value: 'Sam-Bodden', score: 8 }, // { value: 'Norem', score: 10 }, { value: 'Royce', score: 10 }, // { value: 'Castilla', score: 12 }, { value: 'Prickett', score: 14 } // ] const res7 = await client.zRangeByScore('racer_scores', '-inf', 10); console.log(res7); // >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce'] const res8 = await client.zRem('racer_scores', 'Castilla'); console.log(res8); // >>> 1 const res9 = await client.zRemRangeByScore('racer_scores', '-inf', 9); console.log(res9); // >>> 2 const res10 = await client.zRange('racer_scores', 0, -1); console.log(res10); // >>> ['Norem', 'Royce', 'Prickett'] const res11 = await client.zRank('racer_scores', 'Norem'); console.log(res11); // >>> 0 const res12 = await client.zRevRank('racer_scores', 'Norem'); console.log(res12); // >>> 2 const res13 = await client.zAdd('racer_scores', [ { score: 0, value: 'Norem' }, { score: 0, value: 'Sam-Bodden' }, { score: 0, value: 'Royce' }, { score: 0, value: 'Ford' }, { score: 0, value: 'Prickett' }, { score: 0, value: 'Castilla' } ]); console.log(res13); // >>> 3 const res14 = await client.zRange('racer_scores', 0, -1); console.log(res14); // >>> ['Castilla', 'Ford', 'Norem', 'Prickett', 'Royce', 'Sam-Bodden'] const res15 = await client.zRangeByLex('racer_scores', '[A', '[L'); console.log(res15); // >>> ['Castilla', 'Ford'] const res16 = await client.zAdd('racer_scores', { score: 100, value: 'Wood' }); console.log(res16); // >>> 1 const res17 = await client.zAdd('racer_scores', { score: 100, value: 'Henshaw' }); console.log(res17); // >>> 1 const res18 = await client.zAdd('racer_scores', { score: 150, value: 'Henshaw' }, { nx: true }); console.log(res18); // >>> 0 const res19 = await client.zIncrBy('racer_scores', 50, 'Wood'); console.log(res19); // >>> 150.0 const res20 = await client.zIncrBy('racer_scores', 50, 'Henshaw'); console.log(res20); // >>> 200.0
package io.redis.examples; import redis.clients.jedis.UnifiedJedis; import redis.clients.jedis.resps.Tuple; public class SortedSetsExample { public void run() { UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379"); long res1 = jedis.zadd("racer_scores", 10d, "Norem"); System.out.println(res1); // >>> 1 long res2 = jedis.zadd("racer_scores", 12d, "Castilla"); System.out.println(res2); // >>> 1 long res3 = jedis.zadd("racer_scores", new HashMap<String,Double>() {{ put("Sam-Bodden", 8d); put("Royce", 10d); put("Ford", 6d); put("Prickett", 14d); put("Castilla", 12d); }}); System.out.println(res3); // >>> 4 List<String> res4 = jedis.zrange("racer_scores", 0, -1); System.out.println(res4); // >>> [Ford, Sam-Bodden, Norem, Royce, Castil, Castilla, Prickett] List<String> res5 = jedis.zrevrange("racer_scores", 0, -1); System.out.println(res5); // >>> [Prickett, Castilla, Castil, Royce, Norem, Sam-Bodden, Ford] List<Tuple> res6 = jedis.zrangeWithScores("racer_scores", 0, -1); System.out.println(res6); // >>> [[Ford,6.0], [Sam-Bodden,8.0], [Norem,10.0], [Royce,10.0], [Castil,12.0], [Castilla,12.0], [Prickett,14.0]] List<String> res7 = jedis.zrangeByScore("racer_scores", Double.MIN_VALUE, 10d); System.out.println(res7); // >>> [Ford, Sam-Bodden, Norem, Royce] long res8 = jedis.zrem("racer_scores", "Castilla"); System.out.println(res8); // >>> 1 long res9 = jedis.zremrangeByScore("racer_scores", Double.MIN_VALUE, 9d); System.out.println(res9); // >>> 2 List<String> res10 = jedis.zrange("racer_scores", 0, -1); System.out.println(res10); // >>> [Norem, Royce, Prickett] long res11 = jedis.zrank("racer_scores", "Norem"); System.out.println(res11); // >>> 0 long res12 = jedis.zrevrank("racer_scores", "Norem"); System.out.println(res12); // >>> 2 long res13 = jedis.zadd("racer_scores", new HashMap<String,Double>() {{ put("Norem", 0d); put("Sam-Bodden", 0d); put("Royce", 0d); put("Ford", 0d); put("Prickett", 0d); put("Castilla", 0d); }}); System.out.println(res13); // >>> 3 List<String> res14 = jedis.zrange("racer_scores", 0, -1); System.out.println(res14); // >>> [Castilla, Ford, Norem, Prickett, Royce, Sam-Bodden] List<String> res15 = jedis.zrangeByLex("racer_scores", "[A", "[L"); System.out.println(res15); // >>> [Castilla, Ford] long res16 = jedis.zadd("racer_scores", 100d, "Wood"); System.out.println(res16); // >>> 1 long res17 = jedis.zadd("racer_scores", 100d, "Henshaw"); System.out.println(res17); // >>> 1 long res18 = jedis.zadd("racer_scores", 100d, "Henshaw"); System.out.println(res18); // >>> 0 double res19 = jedis.zincrby("racer_scores", 50d, "Wood"); System.out.println(res19); // >>> 150.0 double res20 = jedis.zincrby("racer_scores", 50d, "Henshaw"); System.out.println(res20); // >>> 200.0 } }
package example_commands_test import ( "context" "fmt" "github.com/redis/go-redis/v9" ) func ExampleClient_zadd() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) res1, err := rdb.ZAdd(ctx, "racer_scores", redis.Z{Member: "Norem", Score: 10}, ).Result() if err != nil { panic(err) } fmt.Println(res1) // >>> 1 res2, err := rdb.ZAdd(ctx, "racer_scores", redis.Z{Member: "Castilla", Score: 12}, ).Result() if err != nil { panic(err) } fmt.Println(res2) // >>> 1 res3, err := rdb.ZAdd(ctx, "racer_scores", redis.Z{Member: "Norem", Score: 10}, redis.Z{Member: "Sam-Bodden", Score: 8}, redis.Z{Member: "Royce", Score: 10}, redis.Z{Member: "Ford", Score: 6}, redis.Z{Member: "Prickett", Score: 14}, redis.Z{Member: "Castilla", Score: 12}, ).Result() if err != nil { panic(err) } fmt.Println(res3) // >>> 4 } func ExampleClient_zrange() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) _, err := rdb.ZAdd(ctx, "racer_scores", redis.Z{Member: "Norem", Score: 10}, redis.Z{Member: "Sam-Bodden", Score: 8}, redis.Z{Member: "Royce", Score: 10}, redis.Z{Member: "Ford", Score: 6}, redis.Z{Member: "Prickett", Score: 14}, redis.Z{Member: "Castilla", Score: 12}, ).Result() if err != nil { panic(err) } res4, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result() if err != nil { panic(err) } fmt.Println(res4) // >>> [Ford Sam-Bodden Norem Royce Castilla Prickett] res5, err := rdb.ZRevRange(ctx, "racer_scores", 0, -1).Result() if err != nil { panic(err) } fmt.Println(res5) // >>> [Prickett Castilla Royce Norem Sam-Bodden Ford] } func ExampleClient_zrangewithscores() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) _, err := rdb.ZAdd(ctx, "racer_scores", redis.Z{Member: "Norem", Score: 10}, redis.Z{Member: "Sam-Bodden", Score: 8}, redis.Z{Member: "Royce", Score: 10}, redis.Z{Member: "Ford", Score: 6}, redis.Z{Member: "Prickett", Score: 14}, redis.Z{Member: "Castilla", Score: 12}, ).Result() if err != nil { panic(err) } res6, err := rdb.ZRangeWithScores(ctx, "racer_scores", 0, -1).Result() if err != nil { panic(err) } fmt.Println(res6) // >>> [{6 Ford} {8 Sam-Bodden} {10 Norem} {10 Royce} {12 Castilla} {14 Prickett}] } func ExampleClient_zrangebyscore() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) _, err := rdb.ZAdd(ctx, "racer_scores", redis.Z{Member: "Norem", Score: 10}, redis.Z{Member: "Sam-Bodden", Score: 8}, redis.Z{Member: "Royce", Score: 10}, redis.Z{Member: "Ford", Score: 6}, redis.Z{Member: "Prickett", Score: 14}, redis.Z{Member: "Castilla", Score: 12}, ).Result() if err != nil { panic(err) } res7, err := rdb.ZRangeByScore(ctx, "racer_scores", &redis.ZRangeBy{Min: "-inf", Max: "10"}, ).Result() if err != nil { panic(err) } fmt.Println(res7) // >>> [Ford Sam-Bodden Norem Royce] } func ExampleClient_zremrangebyscore() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) _, err := rdb.ZAdd(ctx, "racer_scores", redis.Z{Member: "Norem", Score: 10}, redis.Z{Member: "Sam-Bodden", Score: 8}, redis.Z{Member: "Royce", Score: 10}, redis.Z{Member: "Ford", Score: 6}, redis.Z{Member: "Prickett", Score: 14}, redis.Z{Member: "Castilla", Score: 12}, ).Result() if err != nil { panic(err) } res8, err := rdb.ZRem(ctx, "racer_scores", "Castilla").Result() if err != nil { panic(err) } fmt.Println(res8) // >>> 1 res9, err := rdb.ZRemRangeByScore(ctx, "racer_scores", "-inf", "9").Result() if err != nil { panic(err) } fmt.Println(res9) // >>> 2 res10, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result() if err != nil { panic(err) } fmt.Println(res10) // >>> [Norem Royce Prickett] } func ExampleClient_zrank() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) _, err := rdb.ZAdd(ctx, "racer_scores", redis.Z{Member: "Norem", Score: 10}, redis.Z{Member: "Royce", Score: 10}, redis.Z{Member: "Prickett", Score: 14}, ).Result() if err != nil { panic(err) } res11, err := rdb.ZRank(ctx, "racer_scores", "Norem").Result() if err != nil { panic(err) } fmt.Println(res11) // >>> 0 res12, err := rdb.ZRevRank(ctx, "racer_scores", "Norem").Result() if err != nil { panic(err) } fmt.Println(res12) // >>> 2 } func ExampleClient_zaddlex() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) _, err := rdb.ZAdd(ctx, "racer_scores", redis.Z{Member: "Norem", Score: 0}, redis.Z{Member: "Royce", Score: 0}, redis.Z{Member: "Prickett", Score: 0}, ).Result() res13, err := rdb.ZAdd(ctx, "racer_scores", redis.Z{Member: "Norem", Score: 0}, redis.Z{Member: "Sam-Bodden", Score: 0}, redis.Z{Member: "Royce", Score: 0}, redis.Z{Member: "Ford", Score: 0}, redis.Z{Member: "Prickett", Score: 0}, redis.Z{Member: "Castilla", Score: 0}, ).Result() if err != nil { panic(err) } fmt.Println(res13) // >>> 3 res14, err := rdb.ZRange(ctx, "racer_scores", 0, -1).Result() if err != nil { panic(err) } fmt.Println(res14) // >>> [Castilla Ford Norem Prickett Royce Sam-Bodden] res15, err := rdb.ZRangeByLex(ctx, "racer_scores", &redis.ZRangeBy{ Min: "[A", Max: "[L", }).Result() if err != nil { panic(err) } fmt.Println(res15) // >>> [Castilla Ford] } func ExampleClient_leaderboard() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) res16, err := rdb.ZAdd(ctx, "racer_scores", redis.Z{Member: "Wood", Score: 100}, ).Result() if err != nil { panic(err) } fmt.Println(res16) // >>> 1 res17, err := rdb.ZAdd(ctx, "racer_scores", redis.Z{Member: "Henshaw", Score: 100}, ).Result() if err != nil { panic(err) } fmt.Println(res17) // >>> 1 res18, err := rdb.ZAdd(ctx, "racer_scores", redis.Z{Member: "Henshaw", Score: 150}, ).Result() if err != nil { panic(err) } fmt.Println(res18) // >>> 0 res19, err := rdb.ZIncrBy(ctx, "racer_scores", 50, "Wood").Result() if err != nil { panic(err) } fmt.Println(res19) // >>> 150 res20, err := rdb.ZIncrBy(ctx, "racer_scores", 50, "Henshaw").Result() if err != nil { panic(err) } fmt.Println(res20) // >>> 200 }
using StackExchange.Redis; public class SortedSetExample { public void run() { var muxer = ConnectionMultiplexer.Connect("localhost:6379"); var db = muxer.GetDatabase(); bool res1 = db.SortedSetAdd("racer_scores", "Norem", 10); Console.WriteLine(res1); // >>> True bool res2 = db.SortedSetAdd("racer_scores", "Castilla", 12); Console.WriteLine(res2); // >>> True long res3 = db.SortedSetAdd("racer_scores", new[]{ new SortedSetEntry("Sam-Bodden", 8), new SortedSetEntry("Royce", 10), new SortedSetEntry("Ford", 6), new SortedSetEntry("Prickett", 14), new SortedSetEntry("Castilla", 12) }); Console.WriteLine(res3); // >>> 4 RedisValue[] res4 = db.SortedSetRangeByRank("racer_scores", 0, -1); Console.WriteLine(string.Join(", ", res4)); // >>> Ford, Sam-Bodden, Norem, Royce, Castilla, Prickett RedisValue[] res5 = db.SortedSetRangeByRank("racer_scores", 0, -1, Order.Descending); Console.WriteLine(string.Join(", ", res5)); // >>> Prickett, Castilla, Royce, Norem, Sam-Bodden, Ford SortedSetEntry[] res6 = db.SortedSetRangeByRankWithScores("racer_scores", 0, -1); Console.WriteLine(string.Join(", ", res6)); // >>> Ford: 6, Sam-Bodden: 8, Norem: 10, Royce: 10, Castilla: 12, Prickett: 14 RedisValue[] res7 = db.SortedSetRangeByScore("racer_scores", double.NegativeInfinity, 10); Console.WriteLine(string.Join(", ", res7)); // >>> Ford, Sam-Bodden, Norem, Royce bool res8 = db.SortedSetRemove("racer_scores", "Castilla"); Console.WriteLine(res8); // >>> True long res9 = db.SortedSetRemoveRangeByScore("racer_scores", double.NegativeInfinity, 9); Console.WriteLine(res9); // >>> 2 RedisValue[] res10 = db.SortedSetRangeByRank("racer_scores", 0, -1); Console.WriteLine(string.Join(", ", res10)); // >>> Norem, Royce, Prickett long? res11 = db.SortedSetRank("racer_scores", "Norem"); Console.WriteLine(res11); // >>> 0 long? res12 = db.SortedSetRank("racer_scores", "Norem", Order.Descending); Console.WriteLine(res12); // >>> 2 long res13 = db.SortedSetAdd("racer_scores", new[] { new SortedSetEntry("Norem", 0), new SortedSetEntry("Sam-Bodden", 0), new SortedSetEntry("Royce", 0), new SortedSetEntry("Ford", 0), new SortedSetEntry("Prickett", 0), new SortedSetEntry("Castilla", 0) }); Console.WriteLine(res13); // >>> 3 RedisValue[] res14 = db.SortedSetRangeByRank("racer_scores", 0, -1); Console.WriteLine(string.Join(", ", res14)); // >>> Castilla, Ford, Norem, Pricket, Royce, Sam-Bodden RedisValue[] res15 = db.SortedSetRangeByValue("racer_scores", "A", "L", Exclude.None); Console.WriteLine(string.Join(", ", res15)); // >>> Castilla, Ford bool res16 = db.SortedSetAdd("racer_scores", "Wood", 100); Console.WriteLine(res16); // >>> True bool res17 = db.SortedSetAdd("racer_scores", "Henshaw", 100); Console.WriteLine(res17); // >>> True bool res18 = db.SortedSetAdd("racer_scores", "Henshaw", 150); Console.WriteLine(res18); // >>> False double res19 = db.SortedSetIncrement("racer_scores", "Wood", 50); Console.WriteLine(res19); // >>> 150.0 double res20 = db.SortedSetIncrement("racer_scores", "Henshaw", 50); Console.WriteLine(res20); // >>> 200.0 } }
You'll see that ZADD
returns 0 when the member already exists (the score is updated), while ZINCRBY
returns the new score. The score for racer Henshaw went from 100, was changed to 150 with no regard for what score was there before, and then was incremented by 50 to 200.
Basic commands
ZADD
adds a new member and associated score to a sorted set. If the member already exists, the score is updated.ZRANGE
returns members of a sorted set, sorted within a given range.ZRANK
returns the rank of the provided member, assuming the sorted is in ascending order.ZREVRANK
returns the rank of the provided member, assuming the sorted set is in descending order.
See the complete list of sorted set commands.
Performance
Most sorted set operations are O(log(n)), where n is the number of members.
Exercise some caution when running the ZRANGE
command with large returns values (e.g., in the tens of thousands or more).
This command's time complexity is O(log(n) + m), where m is the number of results returned.
Alternatives
Redis sorted sets are sometimes used for indexing other Redis data structures. If you need to index and query your data, consider the JSON data type and the Redis Query Engine features.
Learn more
- Redis Sorted Sets Explained is an entertaining introduction to sorted sets in Redis.
- Redis University's RU101 explores Redis sorted sets in detail.