Redis Datatypes and Commands-Sorted Set

Redis Datatypes and Commands – Sorted Set

Redis stores the data as key value pair. Keys can be any binary value and it is represented as ASCII strings for easily understandable and readability purpose. Redis supports five different datatypes and anyone of the datatype can be represented as value.

datatypes

Redis supports five different datatypes and they are given below. Each datatype can be used in Redis with different set of commands.

  • String
  • List
  • Set
  • Sorted Set
  • Hash

Sorted set

The Sorted Set datatype is used to maintain the order of the elements in ascending order.

zadd

The ZADD command is used to add the data into the key set. Use the below command to add the data into the key set.

Syntax
zadd <keyname> <score1> <member1> <score2> <member2> ... N

Example
zadd players 20 John 30 Amar 10 Mike
ZADD command

zrange

The ZRANGE command is used to view all the elements from the ordered key set. Use the below command to view all the elements from the key set.

Syntax
zrange <keyname> start stop

Example
zrange players 0 -1
ZRANGE command

The Start and Stop represents the index of the elements. The 0 to -1 represents to view all the elements from the set.

Execute the below command, to view all the elements from the set with “WITHSCORES” option.

Syntax
zrange <keyname> start stop withscores

Example
zrange players 0 -1 withscores
Zrange with scores

zcard

The ZCARD command is used to return the number of elements from the ordered key set. Use the below command to view the number of elements from the set.

Syntax
zcard <keyname>

Example
zcard players
ZCARD command

zcount

The ZCOUNT command is used to return the count of elements from the ordered key set. Use the below command to view the count of elements from the key set.

Syntax
zcount <keyname> -inf +inf

Example
zcount players -inf +inf
ZCOUNT command

zrank

The ZRANK command is used to find out the index of the element in the ordered key set. Use the below command to get the index of the element.

Syntax
zrank <keyname> member

Example
zrank players Amar
ZRANK command

zscore

The ZSCORE command is used to return the score of the member from the ordered key set. Use the below command to return the score of the member.

Syntax
zscore <keyname> member

Example
zscore players Amar
ZSCORE command

zrem

The ZREM command is used to remove the elements from the ordered set. Use the below command to remove the elements from the set.

Syntax
zrem <keyname> member

Example
zrem players Amar
ZREM command

Execute the below command to get the all the elements from the ordered set after remove the member from the key set.

zrange players 0 -1
ZRANGE command

We have learned and executed the Redis Sorted Set datatype commands.

How useful was this post?

Click on a star to rate it!

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

Advertisements

Post your comments