w3resource

Redis Sorted Sets: ZSCAN

Redis ZSCAN Command

Redis ZSCAN command iterates elements of Sorted Set types and their associated scores.

Basic usage of SSCAN

  • ZSCAN is a cursor based iterator. This means that at every call of the command, the server returns an updated cursor that the user needs to use as the cursor argument in the next call.
  • An iteration starts when the cursor is set to 0, and terminates when the cursor returned by the server is 0. The following is an example of ZSCAN iteration:

Here are some common uses and scenarios for the "ZSCAN" command:

  • Iterating Over Elements: Efficiently iterate over large sorted sets without blocking the server.
  • Data Inspection: Inspect elements and their scores in a sorted set for debugging or analysis.
  • Batch Processing: Process elements in batches to avoid loading the entire set into memory at once.
  • Filtered Searches: Use match patterns to filter and retrieve specific elements during iteration.

Syntax:

ZSCAN key cursor [MATCH pattern] [COUNT count]

Available since

2.8.0.

Return Value

Array reply.

Return Value Type

Array

Example: Redis ZSCAN

127.0.0.1:6379> ZADD mytestset 1 M1 2 M2 3 M3 4 N1 5 N2 6 N3 7 O1 8 O2 9 O3
(integer) 9
127.0.0.1:6379> ZSCAN mytestset 0
1) "0"
2)  1) "M1"
    2) "1"
    3) "M2"
    4) "2"
    5) "M3"
    6) "3"
    7) "N1"
    8) "4"
    9) "N2"
   10) "5"
   11) "N3"
   12) "6"
   13) "O1"
   14) "7"
   15) "O2"
   16) "8"
   17) "O3"
   18) "9"

Example: Redis ZSCAN: using count

127.0.0.1:6379> ZSCAN mytestset 0 COUNT 5
1) "0"
2)  1) "M1"
    2) "1"
    3) "M2"
    4) "2"
    5) "M3"
    6) "3"
    7) "N1"
    8) "4"
    9) "N2"
   10) "5"
   11) "N3"
   12) "6"
   13) "O1"
   14) "7"
   15) "O2"
   16) "8"
   17) "O3"
   18) "9"

Example: Redis ZSCAN: using pattern

127.0.0.1:6379> ZSCAN mytestset 0 COUNT 5
1) "0"
2)  1) "M1"
    2) "1"
    3) "M2"
    4) "2"
    5) "M3"
    6) "3"
    7) "N1"
    8) "4"
    9) "N2"
   10) "5"
   11) "N3"
   12) "6"
   13) "O1"
   14) "7"
   15) "O2"
   16) "8"
   17) "O3"
   18) "9"
127.0.0.1:6379>
127.0.0.1:6379> ZSCAN mytestset 0 MATCH N*
1) "0"
2) 1) "N1"
   2) "4"
   3) "N2"
   4) "5"
   5) "N3"
   6) "6"
127.0.0.1:6379> ZSCAN mytestset 0 MATCH *3*
1) "0"
2) 1) "M3"
   2) "3"
   3) "N3"
   4) "6"
   5) "O3"
   6) "9"
127.0.0.1:6379> ZSCAN mytestset 0 MATCH *3* COUNT 20
1) "0"
2) 1) "M3"
   2) "3"
   3) "N3"
   4) "6"
   5) "O3"
   6) "9"

Previous: ZUNIONSTORE
Next: Redis HyperLogLog PFADD



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/redis/redis-zscan-key-cursor.php